从MVC 3剃须刀查看变量逃逸单引号 [英] Escaping single quote from an MVC 3 Razor View variable

查看:122
本文介绍了从MVC 3剃须刀查看变量逃逸单引号的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个包含在字符串中item.Name一个变量这是星期二!。
为了减轻JavaScript错误,在C#控制器我已经躲过了这场单引号。
在网页上,出现这样的这\\周二的!。

这至少prevents任何JavaScript错误,但是,我不想实际字符串显示包含逃脱它反斜线。

我怎么可能能够恢复曾经的JavaScript错误已经得到照顾的逃避?这感觉就像一个相当简单的问题,但我有点不熟悉MVC 3,任何暗示得多AP preciated!我的搜索没有找到我特定于此的任何例子。

在剃刀查看我的code的一个例子:

  @foreach(以型号VAR项)
{
    @ Html.DisplayFor(modelItem => item.Name)// item.Name =这\\周二的!
}


解决方案

创建,您可以使用或干脆带$ C $直接℃的扩展方法。我不会带code中的视图之前得到它,除非你有你的视图模型)一个单独的属性意味着这个(不是一个坏主意(

这是未经测试,但这些方针的东西。



公共静态类HtmlExtensions{
    公共静态IHtmlString JavaScriptEn code(这个HTML的HtmlHelper,串项)
    {
        返回新HtmlString(HttpUtility.JavaScriptStringEn code(项目));
    }
}

您可以然后只需调用@ Html.JavaScriptEn code(yourProperty)从视图或只是引用您的EN codeD属性的名称。

I have a variable within item.Name that contains the string "It's Tuesday!". To alleviate javascript errors, in the c# controller I have already escaped this single quote. On the webpage, it appears like this "It\'s Tuesday!".

This at least prevents any javascript errors, however, I do not want the actual string displayed to contain the backslash that has escaped it.

How might I be able to revert the escaping once the javascript errors have already been taken care of? This feels like a rather simple problem, but I am a bit unfamiliar with MVC 3. Any hint is much appreciated! My searching 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\'s Tuesday!"
} 

解决方案

Create an extension method you can use or simply encode directly. I would not encode prior to the view getting it unless you have a separate property in your viewmodel meant for this (not a bad idea()

This is not tested but something along these lines


public static class HtmlExtensions

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

You can then just call @Html.JavaScriptEncode(yourProperty) from the view or simply reference your encoded property name.

这篇关于从MVC 3剃须刀查看变量逃逸单引号的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆