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>