update .html with @HTML helper DropDownList

醉酒当歌 提交于 2020-01-16 05:24:28

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!