ASP.NETMVC View page Serialization C # Model as JSON string

Source: Internet
Author: User
Tags parse string

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 &quote; Direct use of json.parse () parsing will cause an errorvarstr2= "@str2"; varDatauser=str; varReg= NewRegExp ("&quot;", "g"); //Create a regular RegExp object        varData=Json.parse (Datauser.replace (Reg,'"')///The &quote; 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

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.