gpt4 book ai didi

javascript - 没有 Razor 编码的 MvcHtmlString

转载 作者:行者123 更新时间:2023-11-28 00:31:36 26 4
gpt4 key购买 nike

我正在编写一个生成 JavaScript 代码并发送 Razor View 的方法。但是 razor view 根据其 head 对其进行编码。代码如下。

这是我的方法体,返回一个 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() 作为解决方案。我想在服务器端进行此操作。

最佳答案

您是否考虑过使用部分 View ?

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

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)

关于javascript - 没有 Razor 编码的 MvcHtmlString,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28930330/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com