Qwofer
Qwofer

Reputation: 73

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'";

Output the data in section JS code. But when viewing the source code of the page in the browser, not getting what wanted. What's the problem? How to make a normal quotes?

JS: "data": "@organizations"

Result in view webpage returned "data": "'Passport':'14f0eac0-43eb-4c5f-b9fe-a09d2848db80','Bank':'ad1d77d8-7eb1-4a4c-9173-b0f2f7269644'"

Upvotes: 4

Views: 1822

Answers (4)

shannon
shannon

Reputation: 8784

In your code example here, the culprit is the

@organizations

that generates the quotes. You could instead use:

@Html.Raw(organizations)

Okay, that's great, but by creating JSON, you are doing work the framework could be doing for you. You probably want a model that the framework can serialize for you. This way you don't even need any code in your view header 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 NuGET into your project because Microsoft is moving to it. No point in figuring out how to use the old JSON serializer to do this. Also note that unless you are using the model for other purposes, you might choose to do the dictionary conversion outside the view, reducing the code-work in the view.

Next, if you are embedding JSON in the view, you might want to consider one of two other options. If the amount of data will be small, consider using the join method proposed by eli (here), but instead encoding it in HTML 5 "data-" elements and loading it using JavaScript. That way you keep javascript out of your view. It's just one more step of confusing when debugging javascript, looking for variables that are initialized by dynamically-generated HTML.

Better yet, create a reusable HTML helper method to transform 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 the data separately. Render it with a simple Json() method in your controller, and get it with a simple jQuery $.json() in your client-side code. See here for an example

Good luck!

Upvotes: 0

Elyor
Elyor

Reputation: 865

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)

Upvotes: 2

Craig
Craig

Reputation: 36836

What if you change

"data": "@organizations"

to

"data": "@Html.Raw(organizations)"

Upvotes: 1

Related Questions