如何将 Dropdownlist 绑定到 webgrid 中的新行?

How to bind a Dropdownlist to new row in webgrid?

是否可以在添加到WebGrid 的新行中提供下拉列表?我尝试添加这个

'<td >@Html.DropDownList("Team", (IEnumerable<SelectListItem>)ViewBag.Teams, "")</td>'

它说

Uncaught SyntaxError: Invalid or unexpected token at <td ><select id="Team" name="Team"><option value=""></option>.

代码:

var row = '<tr class="webgrid-row-style">'+
          '<td class="col3Width"><input type="text" id="Date" value=""     class="edit-mode date-picker" /></td>' +
          '<td >@Html.DropDownList("Team", (IEnumerable<SelectListItem>)ViewBag.Teams, "")</td>' +
          '<td ><span><input type="text" id="Name" value="" class="edit-mode /></span></td>' +
          '<td ><span><input type="text" id="Category" value="" class="edit-mode/></span></td>' +
          '<td ><span><input type="text" id="Received_Count" value="" class="edit-mode" /></span></td>' +
          '<td ><span><input type="text" id="Done_Count" value="" class="edit-mode" /></span></td>' +
          '<td ><button class="add-item edit-mode">Add</button>&nbsp;<button class="remove-item edit-mode">Cancel</button></td>' +
          '</tr>';

$('table tbody:last').append(row);

错误:

当您在 javascript 字符串中使用 @Html.DropDownList 时,例如

'<td >@Html.DropDownList("Team", (IEnumerable<SelectListItem>)ViewBag.Teams, "")</td>'

它生成一个多行字符串,如下所示

'<td ><select id="Team" name="Team"><option value=""></option>
 <option>Sukantha</option>
 <option>Shruti</option>
 <option>Shilpa</option>
 <option>Sachin</option>
 <option>Ramya</option>
 <option>Nishmitha</option>
 <option>Mahesh</option>
 </select></td>'

这是无效的,因此你得到了错误。

作为解决方法,请尝试将 @Html.DropDownList 放置在您视图中某处的隐藏 div 中

<div id="divTeams" style="display: none;">
    @Html.DropDownList("Team", (IEnumerable<SelectListItem>)ViewBag.Teams, "")
</div>

然后使用 $('#divTeams').html()

获取生成的字符串
var row = '<tr class="webgrid-row-style">'+
          '<td class="col3Width"><input type="text" id="Date" value=""     class="edit-mode date-picker" /></td>' +
          '<td >' + $('#divTeams').html() + '</td>' +
          '<td ><span><input type="text" id="Name" value="" class="edit-mode /></span></td>' +
          '<td ><span><input type="text" id="Category" value="" class="edit-mode/></span></td>' +
          '<td ><span><input type="text" id="Received_Count" value="" class="edit-mode" /></span></td>' +
          '<td ><span><input type="text" id="Done_Count" value="" class="edit-mode" /></span></td>' +
          '<td ><button class="add-item edit-mode">Add</button>&nbsp;<button class="remove-item edit-mode">Cancel</button></td>' +
          '</tr>';

$('table tbody:last').append(row);