Quotes in Asp.NET MVC View

In view

@{ Layout = "~/Views/Shared/site.cshtml"; ViewBag.Title = "Organizations"; var organizations = ""; foreach (var org in Model) { organizations += "'" + org.Name + "':'" + org.Id + "',"; } organizations = organizations.Substring(0, organizations.Length - 1); } 

Result operation: organizations = "'Passport':'14f0eac0-43eb-4c5f-b9fe-a09d2848db80','Bank':'ad1d77d8-7eb1-4a4c-9173-b0f2f7269644'";

Print data in the JS code section. But when viewing the source code of the page in the browser, it does not work out what is needed. What is the problem? How to make normal quotes?

JS: "data": "@organizations"

The result in the web page view is returned "data": "'Passport':'14f0eac0-43eb-4c5f-b9fe-a09d2848db80','Bank':'ad1d77d8-7eb1-4a4c-9173-b0f2f7269644'"

+4
source share
4 answers

OK cool Q, try this source:

 @{ var model = Model.ToArray().Select(org => string.Format("'{0}':'{1}'", org.Name, org.Id)); var data = string.Join(",", model); } @Html.Raw(data) 
+2
source

What if you change

 "data": "@organizations" 

to

 "data": "@Html.Raw(organizations)" 
+1
source

In the sample code here, the culprit is

 @organizations 

which generates quotes. Instead, you can use:

 @Html.Raw(organizations) 

Ok, this is great, but by creating JSON, you are doing the work that the framework can do for you. You probably need a model that the system can serialize for you. That way, you don't need any code in the title of your view at all.

 @Html.Raw(JsonConvert.SerializeObject(Model.ToDictionary(m => m.Name, m => m.Id)))) 

Above, note that I'm using Json.NET, which you probably want to use NuGET in your project, because Microsoft is moving towards it. It makes no sense to determine how to use the old JSON serializer for this. Also note that if you are not using the model for other purposes, you can choose to transform the dictionary outside the view, reducing the code in the view.

Further, if you embed JSON in a view, you can consider one of two other options. If the amount of data is small, consider the connection method method proposed by eli (here) , but instead encode it in the "data-" elements of HTML 5 and load it using JavaScript. This way you save javascript from your view. This is another step to confusing javascript debugging, looking for variables that are initialized by dynamically generated HTML.

Better yet, create a reusable HTML helper to convert your model into data attributes: How to use dashes in HTML-5 data attributes in ASP.NET MVC

Finally, if there are MANY JSON elements, consider sending data separately. Provide it with a simple Json () method in your controller and get it with a simple jQuery $ .json () in your client code. See here for an example.

Good luck

0
source

Source: https://habr.com/ru/post/1432625/


All Articles