开发者

How can I return a list/array/Json object of id's from the controller in the ViewBag and add it to the htmlAttributes of an actionlink?

开发者 https://www.devze.com 2023-03-31 05:38 出处:网络
I have an Action which returns a partial view, and I would like to store a list of id\'s in the ViewBag.property = ids (somewhere temporary) and add them to an actionLink into the object HtmlAttribute

I have an Action which returns a partial view, and I would like to store a list of id's in the ViewBag.property = ids (somewhere temporary) and add them to an actionLink into the object HtmlAttributes

How can this be done, or is there a better way to do this?

public PartialViewResult MyAction() {
    // do something and return a partialview
    List/Array/Dictionary ids;  // ?
    foreach开发者_开发知识库 (MyClass c in List<MyClass>) { 
        // Doing something else but need to store the ID somewhere for the ActionLink
        ids[] =c.Id ?
        ids.Add(c.Id) = c.Id; ?
    }
    ViewBag.myProperty = ? //(e.g. some List or Array to Json?)
}

In the partialview

@Html.ActionLink("action", ..., new { idArray = @ViewBag.myProperty } )

Is this possible, or is there a better alternative? Can this be done passing a Json object to the htmlAttributes in an actionLink?

System.Web.Script.Serialization.JavaScriptSerializer oSerializer = new    
    System.Web.Script.Serialization.JavaScriptSerializer();
string sJSON = oSerializer.Serialize(ids);
ViewBag.myProperty = sJSON;


I would use the session (HttpContext.Current.Session) to store a variable like this instead of viewbag. This way, you would not attach the array to the link, just the session key.

In the code:

string mylistkey = ?;//choose a meaningful and unique key name
HttpContext.Current.Session.add(mylistkey, list); //your list in your example
ViewBag.myProperty = mylistkey; // just put the key in the viewbag

In the pagecode:
@Html.ActionLink("action", ..., new { idSessionKey = @ViewBag.myProperty } )

In your target page, you use the key to retrieve the actual array from the session:
string sessionKey = HttpContext.Current.Request.QueryString[idSessionKey];
List<MyClass> mylist=(List<MyClass>)(
HttpContext.Current.Session[sessionKey]);
HttpContext.Current.Session.Remove(sessionKey);

There are many other ways to do this, and I think you can make your JSON idea work as well. This would be my suggestion because it keeps your URL line more readable.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号