Json.Net object passed to View in ViewData
I have a page in which I've implemented an ajax call to a controller that returns search results that are packaged in a JsonNetResult.
I have a lot of javascript to then deal with the return package, iterating over each item in the results set and outputting to the page.
Now, however, I need to implement the usage of these same methods for a single item that will be known on page load. I'd like to just pass this info to the View in a ViewData dictionary.
However, I don't know how to use Json.Net in this way.
How do I load a Json.Net object into a native json variable on page load, assuming that object has been stuffed into ViewData["DeepLinkedMessage"]?
I started to go down the path of this:
var thisMessage = (from userMessageProduct .... more linq2sql stuff...);
bool success = (thisMessage.Count() == 0) ? false : true;
var returnPackage = new { success = success, results = thisMessage };
JavaScriptSerializer serializer = new JavaScriptSerializer();
ViewData["DeepLinkedMessage"] = serializer.Serialize(returnPackage);
It worked just fine. But I quickly noticed I'd have to solve the date formatting problems that I'd already solved when I set up the ajax call that returned JsonNetResult. I want to use the exact same methods that I'm using now.
So, I started down this path:
JsonNetResult jsonNetResult = new JsonNetResult();
jsonNetResult.SerializerSettings.Converte开发者_开发百科rs.Add(new IsoDateTimeConverter());
jsonNetResult.Data = returnPackage;
ViewData["DeepLinkedMessage"] = jsonNetResult.ToString();
Then, in my view:
<script type="text/javascript">
deepLinkedMessageId = '<%=ViewData["DeepLinkMessageId"] %>';
deepLinkedMessageRaw = '<%=ViewData["DeepLinkedMessage"]%>';
</script>
But this is returning this:
<script type="text/javascript">
deepLinkedMessageId = '1';
deepLinkedMessageRaw = 'WebUI.Controllers.JsonNetResult';
</script>
While I'm looking for something like this:
<script type="text/javascript">
deepLinkedMessageId = '1';
deepLinkedMessageRaw = '{"success":true,"results":[{"UserId":1,"InternalId":"1356935180","FirstName":"Scott","LastName":"Roberson","MessageId":1,"MessageText":"i just love your product!!!", "MessageCreateTime":"\/Date(1295289549930)\/","ProductId":5,"Flavor":"Almonds","ActivePixel":false,"ActiveClass":null,"TileNumber":0}]}';
</script>
Help using Json.Net for this?
Thanks.
Well, I found out from here that I can just do this:
bool success = (thisMessage.Count() == 0) ? false : true;
var returnPackage = new { success = success, results = thisMessage };
ViewData["DeepLinkedMessage"] = JsonConvert.SerializeObject(returnPackage, new IsoDateTimeConverter());
<wipes hands> "problem solved!"
You should set your view to implement your model explicitely:
Inherits="System.Web.View<YourModelName>"
Then in your view you can do
Model.Property
I just find this easier to isolate where the problem is happening (plus viewdata can be a pain in the ass)
精彩评论