1

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
  • +1 for demonstrating that Razor can be injected into Javascript literals. Shame it only works in the simpler cases. Jul 30, 2013 at 8:23

1 Answer 1

8

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.

1
  • Thanks HiTech. I wished I had checked the post again 3 hours ago. I just spent the whole morning coming up with another work around. I plugged in your code and it works and is simpler than the work around I was just about to post as the answer.
    – Joe
    Jul 29, 2013 at 19:57

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.