The Json.NET library allows the simple and safe reading and writing of JSON objects from .NET. Using readers and writers, and makes passing messages between .NET and JavaScript a snap.
I have the user class like below,
public class User
{
public int UserId { get; set;}
public string Name { get; set;}
public string Note { get; set;}
}
If I want to serialize a list of user directly to web page, so javascript can further process it, I can call SerializeObject in the view:
Newtonsoft.Json.JsonConvert.SerializeObject(Model.Users)
This will render the following string to browser:
[{"UserId":"1","Name":"Tom","Note":"Great!"},{"UserId":"2","Name":"Jim","Note":"Sweet!"}]
In the view, I render a dropdown of user,
<% = Html.DropDownListFor(m => m.UserId,
Model.Users.Select(p => new SelectListItem
{
Text = p.Name,
Value = p.UserId.ToString(),
Selected = p.UserId == Model.UserId
}), "Please Select", new { onchange = "onUserChange(this.value);" })%>
In the user dropdown, if the user was changed, I update the note for this user by javascript, without going back to server
Because we are using Json in the view, be sure to add the namespace to web.config,