0

I want to provide html helper to innerHTML . But can not able to do so.Here is my code.How to solve this

element.innerHTML = '@Html.DropDownList("TopTags", null, new { @onchange = "ChangeCallback(this.value);" })'
AL-zami
  • 7,637
  • 11
  • 53
  • 104
  • I've updated my answer. My original code produced quotes within the quotes which is just wrong. This should now be corrected. – haindl Oct 03 '17 at 13:39

2 Answers2

0
<script id="anything" type="text/template">
        @Html.DropDownList("TopTags", null, new { @onchange = "ChangeCallback(this.value);" })
</script>
<script>
     ....
     element.innerHTML=document.getElementById("anything").innerHTML;
</script>
erdi yılmaz
  • 316
  • 1
  • 3
  • 13
  • Anything inside ` – haindl Oct 03 '17 at 11:29
  • @haindl I think now it can be help – erdi yılmaz Oct 03 '17 at 12:26
  • That's a bit better but there's still one major issue: The OP didn't state that he uses jQuery. The tags only specify ASP.NET MVC. If the OP doesn't use jQuery then he surely won't change his application architecture just to make one simple call that can be solved very simple without jQuery. – haindl Oct 03 '17 at 12:36
  • Remove jquery from my answer – erdi yılmaz Oct 03 '17 at 12:43
  • Excuse me, but have you even tried your own code? I'm getting the JavaScript error `Uncaught TypeError: Cannot read property 'innerHTML' of null`. That's because ` – haindl Oct 03 '17 at 13:01
  • @haindl already try my code. But writing here make mistake. I wrote innerHtml instead of innerHTML – erdi yılmaz Oct 03 '17 at 13:24
  • Yes, `innerHtml ` instead of `innerHTML` was another error. But you still need to change the order of your ` – haindl Oct 03 '17 at 13:28
  • You are right change my blocks. Next time I coppy paste from my editor. No write again here. Thanks. – erdi yılmaz Oct 03 '17 at 13:30
0

@Html.DropDownList() will generate multiple lines of HTML code. You need to encode this output so that JavaScript can understand it.

The following should do the trick:

element.innerHTML = '@HttpUtility.JavaScriptStringEncode(Html.DropDownList("TopTags", null, new { @onchange = "ChangeCallback(this.value);" }).ToHtmlString().Replace("\"", "'"))';
haindl
  • 2,873
  • 2
  • 19
  • 29