您可以使用MVC SelectList对象来生成下拉列表控件,并使用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的用法。这些将用于生成所需的DropDownList。您可以通过提供值列表来限制selectlist的选项(请参见
允许的房间值
)
接下来,在“编辑”视图中,使用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异常。实现这一点的最佳方法是通过构造函数和setter,我在ViewModel中实现了这一点。
最后,您需要在控制器的后编辑操作中更新您的模型:
[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();
}
}
我省略了所有的数据验证资料,你明白了!哎呀!