for循环中的dropdownlist,如何有不同的选择ID?在MVC中

时间:2015-05-24 19:00:46

标签: asp.net-mvc

我的视图中有5个下拉列表,其中包含相同的数据,我只想更改所选的选择ID和选择ID!

如何在视图和控制器中进行此操作? 这条线需要改变

viewModel.TestSelectList = new SelectList(list, "Value", "Text",r.Next(1, 3));

我正在使用mvc5

查看

   @for (int i = 0; i < 5; i++)
    {
     @Html.DropDownListFor(n => n.TestId, Model.TestSelectList)
    }

控制器

public ActionResult Edit()
{
 var viewModel = new TestView();
 List<SelectListItem> list = new List<SelectListItem>() {
  new SelectListItem(){ Selected = false,Value="1", Text="ActionScript"},
  new SelectListItem(){ Selected = false,Value="2", Text="AppleScript"},
  new SelectListItem(){ Selected = true, Value="3", Text="Asp"},
        };
 Random r = new Random();
 viewModel.TestSelectList = new SelectList(list, "Value", "Text",r.Next(1, 3));
}

public class TestView
{
    public int TestId { get; set; }
    public SelectList TestSelectList { get; set; }
}

1 个答案:

答案 0 :(得分:0)

你可以试试这个。

查看

@for (int i = 0; i < 5; i++)
{ 
     var generateRandomId = "testId" + i;
     @Html.DropDownListFor(n => n.TestId, Model.TestSelectList, new { @id = generateRandomId})
}