Asp.net MVC和JQuery的帮助 [英] Help with asp.net mvc and jquery
问题描述
$("#add_activity").click(function () {
$('#activities').append('@Html.Raw(Html.Partial("MyPartial").ToHtmlString())');
});
如果部分是这样的,我有这段代码似乎工作得很好:
I have this bit of code that seems to be working just fine if the partial is this:
<tr><td>Foo</td><td><input type="text" name="bar" /></td></tr>
但如果部分是这样,则无法工作
But fails to work if the partial is this
<tr>
<td>
Foo
</td>
<td>
<input type="text" name="bar" />
</td>
</tr>
如何解决这个问题?..将所有内容放在一行中是很糟糕的.
How can I get around this??.. Having it all in one line is terrible.
请帮助.
推荐答案
这很正常.如果您查看所生成页面的源代码,则会看到以下内容:
That's normal. If you view the source code of your generated page you will see this:
$('#activities').append('
<tr>
<td>
Foo
</td>
<td>
<input type="text" name="bar" />
</td>
</tr>
');
显然与可以视为有效javascript的内容相距甚远.
which obviously is very far from something that could be considered as valid javascript.
您可以使用 JavaScriptStringEncode 方法像这样:
You could use the JavaScriptStringEncode method like this:
$("#add_activity").click(function () {
$('#activities').append('@HttpUtility.JavaScriptStringEncode(Html.Partial("MyPartial").ToHtmlString())');
});
它将正确编码HTML字符串,并且您将获得有效的javascript:
which will take care of properly encoding the HTML string and you will end up with valid javascript:
$("#add_activity").click(function () {
$('#activities').append('\u003ctr\u003e\r\n \u003ctd\u003e\r\n Foo\r\n \u003c/td\u003e\r\n \u003ctd\u003e\r\n \u003cinput type=\"text\" name=\"bar\" /\u003e\r\n \u003c/td\u003e\r\n\u003c/tr\u003e');
});
产生预期的结果.
这篇关于Asp.net MVC和JQuery的帮助的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!