问题
MVC4, C#, jQuery, Razor view (.cshtml)
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>
This works fine for a @HTML.EditorFor:
$('#CmpMASttF').html('@Html.EditorFor(m => m.CmpAdrsSt.State) @Html.ValidationMessageFor(m => m.CmpAdrsSt.State) ');
This is the node being updated:
<tr class="CmpMA"><td tate: </td>
<td colspan="4" ><span id="CmpMASttF" class="editor-field"></span> </td></tr>
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>
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)")'
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).
How do you update the .html() of a node with a @HTML.DropDownList?
Thank you
回答1:
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?
Why not inject it into a dummy script template div instead and have your JQuery simply copy it?
<script id="template" type="text/template">
@Html.DropDownList("CmpAdrsSt.State", (IEnumerable<SelectListItem>)ViewBag._State) @Html.ValidationMessageFor(m => m.CmpAdrsSt.State)
</script>
Then copy using:
$('#CmpMASttF').html($('#template').html());
I prefer this to trying to inject HTML into Javascript string literals, as this gives better separation of the UI from the code.
来源:https://stackoverflow.com/questions/17904426/update-html-with-html-helper-dropdownlist