Search code examples
javascriptmodel-view-controllerasp.net-corehtml-helper

Inserting DropDownList helper from javascript


Here is my code

<a class="fa fa-plus fa-lg" onclick="addFilterItem()"></a>

...

<div id="someId"></div>

...

//in a script tag
function addFilterItem() {
    var container = $("#someId");
    var helper = '@Html.DropDownList("something", new SelectList(ViewBag.list), new { @class = "form-control" })';
    container.append("<div>" + helper + "</div>");
    ..
}

The strange thing to me is that I tested with TextBox first like this

var helper = '@Html.TextBox("something")';

And it works. So why doesn't it work with DropDownList as well? And what are some alternatives?

... NEVERMIND, I GOT IT.


Solution

  • So apparently the DropDownList helper returns a string on multiple rows (I used View Source in browser) and using '' or "" just gives you an error (string unfinished). After looking at ways to write strings on multiple rows in javascript I found ``. The backticks. So writing it like this fixed it for me

    var helper = `@Html.DropDownList("something", new SelectList(ViewBag.list), new { @class = "form-control" })`;