您可以尝试使用
@foreach (var day in Model.diensten)
{
var currentDay=day;
@Html.DropDownListFor(currentDropDown=>currentDay, new SelectList(ViewBag.Diensten, "PropertyName_Holding_Value", "PropertyName_Holding_DisplayText"), new { })
} //This uses the Lambda Expression. Your dropdown Name/Id would be 1,2,3 etc. based on currentDay value.
OR
@foreach (var day in Model.diensten)
{
var currentDay=day;
var dropdownName=string.Format("diensten[{0}]",day-1); //If you want to model bind the selected dropdown value to input entity in POST request. The final dropdownName format should match the hierarchy of the property inside input entity/object. Even without this name formation, you can still POST the selected value back using Jquery/Javascript.
@Html.DropDownList(dropdownName, new SelectList(ViewBag.Diensten, "PropertyName_Holding_Value", "PropertyName_Holding_DisplayText"), new {})
} //
完整页面提交上的值回发/模型绑定注意事项:为了能够对绑定/POST 返回值到服务器进行建模,与属性相对应的 html 元素名称应呈现如下: 假设如果显示 Employee.Department.Name,则在视图中显示部门名称的文本框名称应该匹配 Department_ReferenceName_Inside_Employee.Name 进行模型绑定。
Model:公开课员工
{
公共 int Id { 得到;放; }
公共字符串名称{获取;放; }
公共字符串城市{获取;放; }
公共部门 EmpDepartment { get;放; }
公共列表子Ordinates { get;放; }
}
公开课部
{
公共字符串名称{获取;放; }
}
控制器:
public class HomeController : Controller
{
public ActionResult Index()
{
ViewBag.Message = "Welcome to ASP.NET MVC!";
//Prepare the model and send it to the view
Employee emp = new Employee { EmpDepartment = new Department { Name = "IT" } };
emp.SubOrdinates = new List<Employee> { new Employee { Name = "Emp1" }, new Employee { Name = "Emp2" } };
return View(emp);
}
[HttpPost]
public ActionResult Index(Employee emp)
{ //Put a break-point here and see how the modified values in view are flowing into emp..
return View(emp);
}
public ActionResult About()
{
return View();
}
}
View:
@model MvcApplication.Models.Employee
@using (Html.BeginForm())
{
@Html.TextBoxFor(m => m.EmpDepartment.Name)
@Html.LabelForModel("SubOrdinates :")
for (int i = 0; i < @Model.SubOrdinates.Count; i++)
{
@Html.TextBoxFor(m => (m.SubOrdinates[i].Name))
}
<input type="submit" name="name" value="Submit" /> }
查看源代码/页面源代码:上面的文本框语法将呈现为:
<input id="EmpDepartment_Name" name="EmpDepartment.Name" type="text" value="IT" /> <!--See above html : name=EmpDepartment.Name -->
<label for="">SubOrdinates :</label>
<input id="SubOrdinates_0__Name" name="SubOrdinates[0].Name" type="text" value="Emp1" />
<input id="SubOrdinates_1__Name" name="SubOrdinates[1].Name" type="text" value="Emp2" /> <!--See above html for how collection item Name(s) are being renderd by view engine-->
<input type="submit" name="name" value="Submit" />