【问题标题】:MvcHtmlString without Razor Encoding没有 Razor 编码的 MvcHtmlString
【发布时间】:2015-03-08 18:37:31
【问题描述】:

我正在编写一个生成 javascript 代码并发送剃刀视图的方法。 但是剃须刀视图根据其head.Codes对其进行编码。

这是我的方法体,返回一个 mvchtmlstring:

StringBuilder scriptHtml = new StringBuilder();
        scriptHtml.Append("<script>");
        scriptHtml.Append(@"var {0} = {{
                    id: 'someText',
                    title: '{1}',

                 $(document).ready(function () {{
                       $.function({0});
                   }});");

        scriptHtml.Append("</script>");
var output = string.Format(scriptHtml.ToString(), this.Id, this.Title);
return MvcHtmlString.Create(output);

所以现在,它的输出是:

@&lt;script&gt;var tlyPageGuide,,&quot;direction&quot;:&quot;Right&quot;

这样的东西随着编码的增长而增长。

这就是我想要的,在创建 cshtml 时 Razor 不应该更改我的代码,我必须得到带有渲染的纯 javascript 代码。

注意:我不想使用 Html.Raw() 作为解决方案。我想在服务器端进行。

【问题讨论】:

  • “在服务器端”是什么意思?在服务器端呈现的所有 Razor 视图。
  • 我的意思是,我不希望视图中有任何额外的 Html.Raw() 代码。例如,我想在return MvcHtmlString.Create(output) 或方法体上对其进行编码。顺便一提; Html.Raw() 正在工作,但是当我通过 Helper 像这样 @Html.Raw(Html.MyHelper.MyMethod()) 调用我的方法时,我不想每次都使用它。

标签: javascript c# asp.net-mvc asp.net-mvc-4 razor


【解决方案1】:

您是否考虑过使用局部视图?

例如:(此代码可能包含错误,但您明白了):

class MyScriptModel
{
  public string Id {get;set;}
  public string Title {get;set;}
}

//your partial view: my_partial.cshtml
@model MyScriptModel
//extracted from your string builder
<script>
        var @Model.Id = {{
                    id: 'someText',
                    title: '@Model.Title',

                 $(document).ready(function () {{
                       $.function(@Model.Id);
                   }});

</script>

//instantiate the model
var model = new MyScriptModel {Id="someid", Title="some title"};

//using your partial view
@Html.Partial("my_partial", model)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-10-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-08-28
    相关资源
    最近更新 更多