添加Html.Partial为Javascript [英] Add Html.Partial to Javascript
问题描述
我想设置在Javascript中的字符串与ASP.NET Html.Partial查看。问题是,Html.Partial给出HtmlString,而不是一个JavaScript字符串,我可以处理例如使用jQuery。
的Javascript code:
= MyFunction的函数(){
...
变种badge=@Html.Partial(_ UserBadgeUser.Identity.Name)的ToString();
....
$(#MYNODE)追加(徽章);
};
HTML的部分_UserBadge.cshtml
@model WT.Models.ttUser< DIV的风格=...>
...一些行HTML ...
< / DIV>
我的问题是在开始和+在每一行的末尾不添加。我怎样才能解决这个问题呢?
在code结果:
VAR徽章=
< DIV的风格=...>
...一些行HTML ...
< / DIV取代;
而不是一个JavaScript字符串:
VAR徽章=
'< DIV的风格=...> '+
......一些HTML行......+
'< / DIV> ';
我想你可以使用Json.NET序列化对象JSON(它会逃避所有的字符串中的字符)。
是这样的:
@using Newtonsoft.Json= MyFunction的函数(){
...
变种徽章= @(Html.Raw(JsonConvert.SerializeObject(Html.Partial(_ UserBadgeUser.Identity.Name))));
....
$(#MYNODE)追加(徽章);
};
I want to set a string in Javascript with an ASP.NET Html.Partial View. The problem is that Html.Partial gives an HtmlString and not a Javascript string which i can handle for example with JQuery.
Javascript code:
myfunction= function () {
...
var badge=@Html.Partial("_UserBadge",User.Identity.Name).ToString();
....
$("#myNode").append(badge);
};
Html-Partial "_UserBadge.cshtml":
@model WT.Models.ttUser
<div style="..">
...some more lines html...
</div>
My problem is that ' at beginning and '+ at the end of each line isn't added. How can i resolve the problem?
The code results to:
var badge=
<div style="..">
...some more lines html...
</div>;
instead of a javascript string:
var badge=
'<div style=".."> '+
'...some more lines html... '+
'</div> ';
I think you could use Json.NET for serializing objects to json (it will escape all the string characters).
Something like:
@using Newtonsoft.Json
myfunction= function () {
...
var badge=@(Html.Raw(JsonConvert.SerializeObject(Html.Partial("_UserBadge",User.Identity.Name))));
....
$("#myNode").append(badge);
};
这篇关于添加Html.Partial为Javascript的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!