English 中文(简体)
在javascript 栏目中带上双面字
原标题:Escaping a double-quote in inline c# script within javascript

我需要躲避在javascript内线C#中的两点。 法典如下:

if ("<%= TempData["Message"]%>" == "") {
    // code
};

通常,我只想像这样说:

if ( <%= TempData["Message"]%>  == "") {
    // code
};

然而,TempData[“Message”>在其内有单一报价(其中含有Html.ActionLink()助手在伙伴关系中产生的链接)。 NET MVC。 因此,虽然我可以将“行动链接”的所有助手从TempData[`Message']改为“标签”,但这是一个令人感兴趣的问题,并热衷于听取谁回答。

最佳回答

Call HttpUtility.JavaScriptStringEncode.
This method is new to ASP.Net 4.0; for earlier versions, use the WPL.

问题回答

http://msdn.microsoft.com/en-us/library/system.web.mvc.ajaxhelper.javascriptstringencode.aspx”rel=“nofollow” 缩略语 拉扎尔语中的方法,如:

if ("@Ajax.JavaScriptStringEncode(TempData["Message"].ToString())" == "") {
    // do stuff
}

如果这种说法过于简单,可在/App_Code/JS.cshtml上创建这个小的助手。

@helper Encode(string value) {
    @(HttpUtility.JavaScriptStringEncode(value))
}

您可以从任何观点出发:

@JS.Encode(" single these quotes are encoded ")

我已就此致函一位HtmlHelper,该机将座标编码编码与 Java文可接受的格式挂钩:

public static string JSEncode(this HtmlHelper htmlHelper, string source)
{
    return (source ?? "").Replace(@" ", @" ").Replace(@"""", @"""").Replace(@"&", @"&").Replace(((char)10).ToString(), "<br />");
}

然后,你认为:

if ( <%= Html.JSEncode( TempData["Message"] ) %>  == "") {
    // code
};




相关问题
Anyone feel like passing it forward?

I m the only developer in my company, and am getting along well as an autodidact, but I know I m missing out on the education one gets from working with and having code reviewed by more senior devs. ...

NSArray s, Primitive types and Boxing Oh My!

I m pretty new to the Objective-C world and I have a long history with .net/C# so naturally I m inclined to use my C# wits. Now here s the question: I feel really inclined to create some type of ...

C# Marshal / Pinvoke CBitmap?

I cannot figure out how to marshal a C++ CBitmap to a C# Bitmap or Image class. My import looks like this: [DllImport(@"test.dll", CharSet = CharSet.Unicode)] public static extern IntPtr ...

How to Use Ghostscript DLL to convert PDF to PDF/A

How to user GhostScript DLL to convert PDF to PDF/A. I know I kind of have to call the exported function of gsdll32.dll whose name is gsapi_init_with_args, but how do i pass the right arguments? BTW, ...

Linqy no matchy

Maybe it s something I m doing wrong. I m just learning Linq because I m bored. And so far so good. I made a little program and it basically just outputs all matches (foreach) into a label control. ...

热门标签