使用@HTML助手DropDownList更新.html [英] update .html with @HTML helper DropDownList
问题描述
MVC4,C#,jQuery,剃刀视图(.cshtml)
MVC4, C#, jQuery, Razor view (.cshtml)
我正在尝试使用@ HTML.DropDownList更新节点的.html():
I'm trying to update the .html() of a node with a @HTML.DropDownList:
<script type="text/javascript">
$('#CmpMASttF').html('@Html.DropDownList("CmpAdrsSt.State", (IEnumerable<SelectListItem>)ViewBag._State) @Html.ValidationMessageFor(m => m.CmpAdrsSt.State) ');
</script>
这对于@ HTML.EditorFor可以正常工作:
This works fine for a @HTML.EditorFor:
$('#CmpMASttF').html('@Html.EditorFor(m => m.CmpAdrsSt.State) @Html.ValidationMessageFor(m => m.CmpAdrsSt.State) ');
这是要更新的节点:
<tr class="CmpMA"><td tate: </td>
<td colspan="4" ><span id="CmpMASttF" class="editor-field"></span> </td></tr>
@ HTML.DropDownList代码本身可以正常工作,因此不是问题的根源:
The @HTML.DropDownList code works fine by itself so that is not the source of the problem:
<tr><td>State: </td>
<td colspan="4"><span class="editor-field">
@Html.DropDownList("CmpAdrsSt.State", (IEnumerable<SelectListItem>)ViewBag._State)
@Html.ValidationMessageFor(m => m.CmpAdrsSt.State)</span> </td></tr>
当我尝试使用带有jQuery .html()的@ HTML.DropDownList更新节点时,javascript块中的所有代码均被禁用.
When I try and update the node with the @HTML.DropDownList with the jQuery .html() all the code in the javascript block is disabled.
我尝试对字符串进行编码:
I tried encoding the string:
var test = '@Ajax.JavaScriptStringEncode("Html.DropDownList(\"CmpAdrsSt.State\",(IEnumerable<SelectListItem>)ViewBag._State)")'
但是当注入.html()时,它将呈现为字符串,而不是HTML DropDownList帮助器(在HTML之前添加@,"@ HTML.DropDownList ...,没有区别).
but when injected into the .html() it renders as a string not a HTML DropDownList helper (adding the @ before HTML, "@HTML.DropDownList ..., makes no difference).
如何使用@ HTML.DropDownList更新节点的.html()?
How do you update the .html() of a node with a @HTML.DropDownList?
谢谢
推荐答案
Html帮助程序注入的有趣用法……Html.DropDownList会生成多行,但会生成未终止的javascript字符串.您打算如何解决这个问题?
Interesting use of Html helper injection... The Html.DropDownList generates multiple lines though, generating an unterminated javascript string. How do you plan to get around that?
<script id="template" type="text/template">
@Html.DropDownList("CmpAdrsSt.State", (IEnumerable<SelectListItem>)ViewBag._State) @Html.ValidationMessageFor(m => m.CmpAdrsSt.State)
</script>
然后使用以下副本:
$('#CmpMASttF').html($('#template').html());
与将HTML注入Javascript字符串文字中相比,我更喜欢这样做,因为这样可以更好地将UI与代码分离.
I prefer this to trying to inject HTML into Javascript string literals, as this gives better separation of the UI from the code.
这篇关于使用@HTML助手DropDownList更新.html的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!