-1

I'm trying to build a UI with two dropdowns. The first one is "category", the second one is "sub-category". I can build a static list of "category" in my razor view. I want the "sub-category" item list to be dynamically updated when "category" is changed. I'm trying to pass all category information from server side to client side since the list is not big and there is no security issue. But I cannot find a good way to format my data and transfer it to client side. I can generate a json object with all of my category trees using the following code:

ExpandoObject catToSubcatMap = new ExpandoObject();
foreach (var cat in repository.Categories)
{
            var subcats = repository.SubCategories.Where(s => s.ParentID == cat.CategoryID);
            List<Object> subcatNameList = new List<object>();
            foreach(var subcat in subcats)
            {
                subcatNameList.Add(new { Name = subcat.Name });
            }
            AddProperty(catToSubcatMap, cat.Name, subcatNameList);
}
Session["CatToSubcatMap"] = JsonConvert.SerializeObject(catToSubcatMap, Newtonsoft.Json.Formatting.Indented, new JsonSerializerSettings { NullValueHandling = NullValueHandling.Ignore });

The json itself looks perfect. But when I tried to read the value from my jQuery function, it failed:

var sss = '@Session["CatToSubcatMap"]';

It seems like there are too many special characters in the json string. My generic question is: how should I format and pass complicated data between server and client. Using Viewbag or Session, which one is preferred?

Thanks Chris

myajax95
  • 29
  • 7
  • Have you ever heard of, or worked with, Knockout JS? You can use it to implement a client side MVVM pattern - taking the model data that you use to build the page, converting it to a JavaScript view-model, and then using that to dynamically update elements on the page in response to client updates. I'll see if I can knock out (pun intended) a short explanation here, but check the website: http://knockoutjs.com/ – Graham Harper Feb 15 '17 at 22:29
  • 1
    Refer the second part of [this answer](http://stackoverflow.com/questions/28627421/better-way-to-load-2-dropdown-in-mvc/28640420#28640420) –  Feb 15 '17 at 22:33
  • More specifically, the answer to this question may give you some insight into your specific query about whether to use the ViewBag or the Session: http://stackoverflow.com/questions/12676924/what-is-the-right-time-for-viewdata-viewbag-session-tempdata – Graham Harper Feb 15 '17 at 22:33

1 Answers1

0

You can do what you are trying to do; what you have should be formatted correctly, but you just have to include Html.Raw.

var sss = @(
            Html.Raw(Session["CatToSubcatMap"].ToString())
          );

Raw will essentially write out directly to the response without encoding the contents, which is what likely was happening.

Brian Mains
  • 50,520
  • 35
  • 148
  • 257