这是我的代码
ViewBag.Years= new SelectList(new[]
{ new { ID = "1", Name = "1 Year" },
new { ID = "2", Name = "2 Year" },
new { ID = "3", Name = "3 Year" },
}, "ID", "Name", "");
这里我试图在我的表中为每一行绑定
@for (var i = 0; i < Model.Records.Count; i++ )
{
@Html.DropDownListFor(m => Model[i].Years,
(SelectList)ViewBag.Years})
}
Model [i] .Years为每一行发送不同的值,但仍然没有选择正确的项目。
答案 0 :(得分:1)
public class HomeController : Controller
{
public ActionResult Index()
{
ViewBag.Message = "Welcome to ASP.NET MVC!";
var data = Enumerable.Range(1, 5).Select(a => new myViewModel
{
Description ="Description"+a,
Years =GetYear(a)
}).ToList();
return View(data);
}
private List<SelectListItem> GetYear(int a)
{
return Enumerable.Range(1, 50).Select(y => new SelectListItem
{
Selected = y==a?true:false,
Text = y + " Year",
Value =y.ToString()
}).ToList();
}
public ActionResult About()
{
return View();
}
}
//Model class is bellow
public class myViewModel
{
public string Description { get; set; }
public List<SelectListItem> Years { get; set; }
}
Demo :