1

Javascript 関数内でいくつかのサーバー タグを使用したいと思います。

<%=Model.HtmlProperty%>

In the past I have stored this value in a hidden input field, but when a property contains HTML you get problems with special characters such as quotes. I would like to avoid having to encode and decode in the controller to avoid problems with special characters.

Rick Strahl has a couple posts on this problem in a web forms project, but I'm looking for an elegant solution for an MVC project.

UPDATE: Robert Harvey's answer below suggests to encode the html. Again, that isn't what I want to do. Ultimately, I'm trying to inject html script into an fckeditor instance. This must be done in javascript. I'm trying to figure out how to access the value of <%=Model.HtmlProperty%> inside javascript without storing encoded text in a hidden input element.

4

3 に答える 3

0

私が望んでいたこと(javascript内でサーバータグを使用すること)は不可能のようです。私は文字列を非表示の入力要素内に格納していましたが、queen3のコメントによると、これまでずっと行ってきたことを続けなければならないようです。ご意見ありがとうございます。

于 2010-02-08T16:43:32.510 に答える
0

Rick Strahl の投稿から拝借し、呼び出しシグネチャを少し変更すると、javascript 文字列をエンコードする関数 (Html クラスの拡張メソッドに変更した後) は次のようになります。

public static string EncodeJsString(this HtmlHelper h, string s)
{
    StringBuilder sb = new StringBuilder();
    sb.Append("\"");
    foreach (char c in s)
    {
        switch (c)
        {
            case '\"':
                sb.Append("\\\"");
                break;
            case '\\':
                sb.Append("\\\\");
                break;
            case '\b':
                sb.Append("\\b");
                break;
            case '\f':
                sb.Append("\\f");
                break;
            case '\n':
                sb.Append("\\n");
                break;
            case '\r':
                sb.Append("\\r");
                break;
            case '\t':
                sb.Append("\\t");
                break;
            default:
                int i = (int)c;
                if (i < 32 || i > 127)
                {
                    sb.AppendFormat("\\u{0:X04}", i);
                }
                else
                {
                    sb.Append(c);
                }
                break;
        }
    }
    sb.Append("\"");

    return sb.ToString();
}

次のように呼び出すことができます。

<%= Html.EncodeJsString(Model.HtmlProperty) %>
于 2010-02-05T20:55:43.020 に答える
0

HTMLHelper を使用して、その場でスクリプトを記述します。


public static string WriteLightboxScript(this HtmlHelper helper, string galleryName)
        {
            var builder = new TagBuilder("script");
            builder.MergeAttribute("type", "text/javascript");
            builder.SetInnerText("$(function() {$('a[rel=" + galleryName + "]').lightBox();});");
            return builder.ToString(TagRenderMode.Normal);
        }

于 2010-07-04T14:47:51.130 に答える