您可以使用 MVC SelectList 对象来生成 DropDownList 控件,并使用 Model/ViewModel 模式来将更改持久保存在系统中。
首先,创建用于将数据传递给视图的 ViewModel 类:
public class RoomDetailsViewModel
{
private int _numberOfRooms;
public int NumberOfRooms
{
get { return _numberOfRooms; }
set
{
_numberOfRooms = value;
RoomDetails = new List<SelectList>(_numberOfRooms);
for(int i = 0; i < _numberOfRooms; i++)
RoomDetails.Add(new SelectList(AllowedRoomValues));
}
}
public List<SelectList> RoomDetails { get; set; }
public RoomDetailsViewModel(RoomDetailsModel model)
{
// Get useful info from dataModel
NumberOfRooms = model.NumberOfRooms;
}
public static int[] AllowedRoomValues = new [] {0, 1, 2, 3, 4, 5, 6,7,8,9,10};
}
注意使用 SelectList 的 List。这些将用于生成您需要的 DropDownList。您可以通过提供值列表来限制 SelectList 的选项(请参阅 AllowedRoomValues)。
接下来,在编辑视图中,使用 Html 帮助器来生成下拉列表:
<% using (Html.BeginForm()) {%>
<fieldset>
<legend>Fields</legend>
<p>
<label for="NumberOfRooms">NumberOfRooms:</label>
<%= Html.TextBox("NumberOfRooms", Model.NumberOfRooms) %>
<%= Html.ValidationMessage("NumberOfRooms", "*") %>
</p>
<% for(int i = 0; i < Model.NumberOfRooms; i++)
{ %>
<%= Html.DropDownList("drpRoom" + i,Model.RoomDetails[i]) %>
<% } %>
<p>
<input type="submit" value="Save" />
</p>
</fieldset>
<% } %>
如您所见,您必须确保 RoomDetails 属性永远不会为空,否则您将抛出 NullRef 异常。最好的方法是通过构造函数和设置器,我在 ViewModel 中做到了。
最后,您需要在控制器的 POST Edit 操作中更新模型:
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Edit(int id, FormCollection collection)
{
// Grab the actual data model from your ORM repository of choice here
RoomDetailsModel dataModel = roomDetailRepository.GetItem(r => r.HouseID == id);
try
{
// Updating the model/
for (int i = 0; i < model.NumberOfRooms; i++) // iterate over actual room count
dataModel.RoomDetails[i] = int.Parse(collection["drpRoom" + i]);
// Generate a ViewModel from your actual DataModel in order to display.
RoomDetailsViewModel viewModel = new RoomDetailsViewModel(dataModel);
// display back the view using the viewModel.
return View(viewModel);
}
catch
{
// error handling...
return View();
}
}
为了简洁起见,我省略了所有数据验证的内容,你懂的!哦!