Exclusion of single quote from MVC 3 Razor View variable

I have a variable inside item.Name that contains the string "It Tuesday!". To alleviate JavaScript errors, in the C # controller, I already avoided this separate quote. On a web page, it looks like this: "It's \ Tuesday!".

This at least prevents any javascript errors, however I don't want the actual line to display a backslash that eluded it.

How can I return to escaping after JavaScript errors have been fixed? This seems like a pretty simple problem, but I'm a little unfamiliar with MVC 3. Any tips are really appreciated! My search did not find me any example specific to this.

An example of my code in the Razor view:

@foreach (var item in Model) { @Html.DisplayFor(modelItem => item.Name) // item.Name = "It\ Tuesday!" } 
+6
source share
3 answers

Create an extension method that you can use or just code directly. I would not code before the view if you do not have a separate property in your view model designed for this (not a bad idea ()

This is not verified, but something like that

 public static class HtmlExtensions { public static IHtmlString JavaScriptEncode(this HtmlHelper html, string item) { return new HtmlString(HttpUtility.JavaScriptStringEncode(item)); } }
public static class HtmlExtensions { public static IHtmlString JavaScriptEncode(this HtmlHelper html, string item) { return new HtmlString(HttpUtility.JavaScriptStringEncode(item)); } } 

Then you can simply call @ Html.JavaScriptEncode (yourProperty) from the view, or simply refer to your encoded property name.

+21
source

To prevent output coding, the following can be used again. This, however, relies on you to deal with it yourself yourself.

MVCHTMLString

 @MvcHtmlString.Create(yourString) 
+10
source

I prefer my views to be dull. Therefore, I have a property called "Display" or "DisplayName" that handled the escaping for the view.

0
source

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


All Articles