将jquery与剃刀混合以使用所选选项创建动态添加的选择列表

时间:2011-10-13 11:46:06

标签: jquery asp.net-mvc-3 razor

我想创建具有所选选项属性的选择列表,我希望每次创建另一个选择列表时都增加“i”的值。

var i = -1;
// Hide Section "Loading.gif" On Start 
$(document).ready(function () {
    $("#loading").hide();
    i = i + 1;
    var selects = '@foreach (var selectedone in (System.Collections.IEnumerable)ViewData["Selectlists"]){<tr><td><div id="dive' + i + '"><select name="GroupDetails[' + i + '].cea_id">@foreach(SelectListItem item in (SelectList)ViewData["Suppliers"]){ if(item.Value == selectedone){<option value="@item.Value">@item.Text</option>}else{<option value="@item.Value">@item.Text</option>}}</select></div></td></tr>}'
    /* alert(selects); */
    $("mytable").append(selects);
});

只是为了更容易理解长代码,有这个:

     /* im getting selected options as numeric like = "2","8","6" */
@foreach (var selectedone in (System.Collections.IEnumerable)ViewData["Selectlists"])
{
<tr>
    <td>
     /* also in here i need to increase the value of "i" each time! but couldnt embed it yet */
        <div id="dive' + i + '">
            <select name="GroupDetails[' + i + '].cea_id">

                @foreach(SelectListItem item in (SelectList)ViewData["Suppliers"])
                { 
     /* if each items value is equals to selected options that i putted. Do the code below.*/
                    if(item.Value == selectedone)
                    {   
     /* i wanna add this option selected attribute but not working this way */
                        <option selected="selected" value="@item.Value">@item.Text</option>
                    }
                    else
                    {
     /* other options doesnt need to be selected */
                        <option value="@item.Value">@item.Text</option>
                    }
                }
            </select>
        </div>
    </td>
</tr>
}

1 个答案:

答案 0 :(得分:1)

所以选项是渲染但没有选中它们?在那种情况下,你的平等比较可能会失败吗?您正在比较的值是否正确等于?如果没有,那么它只有在完全同一个对象的同一个实例时才会起作用。