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 fail开发者_开发知识库s 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.
Please help.
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>
');
which obviously is very far from something that could be considered as valid javascript.
You could use the JavaScriptStringEncode method like this:
$("#add_activity").click(function () {
$('#activities').append('@HttpUtility.JavaScriptStringEncode(Html.Partial("MyPartial").ToHtmlString())');
});
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');
});
which produces the desired result.
This works in MVC3:
@{
Layout = null;
var s = HttpUtility.JavaScriptStringEncode(Html.Partial("Banner").ToHtmlString().ToString());
}
<iframe id="banner" src="about:blank" frameborder="0"></iframe>
<script type="text/javascript">
var doc = document.getElementById('banner').contentWindow.document;
doc.open();
doc.write("@Html.Raw(s)");
doc.close();
</script>
精彩评论