ASP. NET MVC, the Controller passes the model to the view, serializes the model into a JSON string in JS, and then uses Json.parse () to parse to JS object, encountering problems:
1. Unexpected token]
2. Unexpected token &
@model MOD. Giftmodel[] @using system.web.script.serialization@{Layout = null;}<!DOCTYPE HTML><HTML><Head> <Metaname= "Viewport"content= "Width=device-width" /> <title>Index</title> <Scriptsrc= "~/scripts/jquery-3.1.1.js"></Script> <Scriptsrc= "~/scripts/knockout-3.4.2.debug.js"></Script> <Script>@Model. ToString (); </Script></Head><Body>@{String str = Newtonsoft.Json.JsonConvert.SerializeObject (Model); The two serialization methods of ASP. String str2 = new JavaScriptSerializer (). Serialize (Model); <text>@str</text> <text>@str2</text> } <Script> varStr= "@str"; In this case, the STR contains a "e; Direct use of json.parse () parsing will cause an errorvarstr2= "@str2"; varDatauser=str; varReg= NewRegExp (""", "g"); //Create a regular RegExp object varData=Json.parse (Datauser.replace (Reg,'"')///The "e; in the string Replace with "alert (data); Alert (typeof(data)); </Script></Body></HTML>
This method is too cumbersome to use, and the JSON () in ASP. NET can pass the view parse string directly;
and the controller passed to the Veiw object into a JS object, I want to experiment, because I want to use knockout directly to the controller passed data to bind to ViewModel, so that no longer use AJAX request data,
Do not know which big God has the more convenient method? Use Ajax to go back to the JSON string I know, what I want to know is that it is a simple way to convert a Controller to a Veiw object into a JS object in the View page.
ASP.NETMVC View page Serialization C # Model as JSON string