Aris
Aris

Reputation: 191

asp.net mvc - How to create multiple DropDownLists using Javascript

I have a Javascript Array of strings and I am trying to create an HTML table to include these strings with dropdowns next to them.

    $.each(data, function (key, val) {
        var tr = $("<tr></tr>");

        $("<td>"+ val + "</td>").appendTo(tr);
        var tmp = '<td>'+'@(Html.DropDownList("SomeDropdown", (SelectList)ViewBag.SomeList))'+'</td>';
        //var tmp = "<td><select><option value="0">Other</option></select> </td>";
        $(tmp).appendTo(tr);
        tr.appendTo("#tableData");
    });

Using HTML works fine, but when I try the same thing using razor I get the exception: "Unterminated string constant". Even if this was to work, the new issue would be that all the DropDownlists would have the same name and id in the generated HTML. Is there a better way to accomplish this?


The main reason I wanted to use Razor for my DropDownList was to use my ViewBag.

The idea is to create a dropdown using HTML and my ViewBag and clone it wherever needed with a new id.

The Javascript:

        var i = 0;
    var prefix = 'pre';
    $.each(data, function (key, val) {
        var tr = $('<tr></tr>');

        var td = $('<td></td>');
        i++;
        var tmp = $("select:first").clone().attr("id", prefix+i);
        tmp.appendTo(td);
        td.appendTo(tr);
        $(td).appendTo(tr);

        tr.appendTo('#tableData');
    });

The HTML (I wrapped the "original" dropdown in a hidden div since it's only necessary to copy):

<div style="display:none">
<select class="selector">
    @foreach (var item in ViewBag.SomeList)
    {
        <option value="@item.Value">
           @item.Text
        </option>
    }
</select>
</div>

Upvotes: 0

Views: 409

Answers (2)

th1rdey3
th1rdey3

Reputation: 4388

I would go for the solution you already have. but i think you can use the razor helper too. like this

<div id='hiddenDiv' style="display:none">
    @(Html.DropDownList("SomeDropdown", (SelectList)ViewBag.SomeList))
</div>

and your javascript

$.each(data, function (key, val) {
        var tr = $("<tr>");
        $("<td>"+ val + "</td>").appendTo(tr);
        $('<td>').append($("#hiddenDiv").find('select').first().clone().attr("id", prefix+(i++)).appendTo(tr);
        tr.appendTo("#tableData");
});

Upvotes: 0

R&#233;da Mattar
R&#233;da Mattar

Reputation: 4381

You can't use Razor in that situation, because Razor is used server side to generate proper html before sending it to client side. @Html.DropDownList can't be executed like that, your browser doesn't understand it. You'd better stick with an html solution.

If you really want to use Razor for this, you can make an ajax request to your server, it will return you a partial view containing your DropDownList, you can insert it wherever you want. But this means communicating with your server, which may not be what you want to do.

Upvotes: 2

Related Questions