我已经能够正确绑定对象列表。工作良好。现在,当我将项目更改为复杂对象时,它将停止工作。
复杂对象是带有对象列表的房间名称。当'回发'时,名称返回正常,但对象列表返回为null。
有任何提示吗?
房型:
public class Room
{
public string Name { get; set; }
public List<Option> Options { get; set; }
public Room() { }
public Room(string name, List<Option> options)
{
Name = name; Options = options;
}
}
选项模型
public class Option
{
public bool IsSelected { get; set; }
public string ImagePath { get; set; }
public int UniqueID { get; set; }
public Option() { }
public Option(bool isSelected, string imagePath, int uniqueID)
{ IsSelected = isSelected; ImagePath = imagePath; UniqueID = uniqueID; }
}
的HomeController
public ActionResult Index()
{
List<Option> options = new List<Option>();
options.Add(new Option(true, "../Content/cars_2.jpg", 4));
options.Add(new Option(true, "../Content/vw_one_liter_concept01_2.jpg", 6));
options.Add(new Option(false, "../Content/00018578.jpg", 8));
//Get a list of selected options and union with all remaining
Room model = new Room("Room1", options);
return View(model);
}
[HttpPost]
public ActionResult Index(Room model)
{
ViewData["results"] = model.Options.Count();
return View(model);
}
索引视图
<%@ Page Language="C#" Inherits="System.Web.Mvc.ViewPage<MultiSelect.Models.Room>" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
<title>Index</title>
<script src="../../Scripts/jquery-1.4.1.js" type="text/javascript"></script>
<script src="../../Scripts/jquery-ui-1.8.10.custom.min.js" type="text/javascript"></script>
</head>
<body>
<% using (Html.BeginForm())
{%>
<%= Html.ValidationSummary(true)%>
<%= Html.TextBoxFor(m=> m.Name) %>
<% Html.RenderPartial("MultiSelect", Model.Options); %>
<% } %>
</body>
</html>
MultiSelect Partial View
<%@ Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl<IList<MultiSelect.Models.Option>>" %>
<% for (int counter = 0;counter< Model.Count(); counter ++)
{ %>
<div class="opt">
<%= Html.HiddenFor(i=> i[counter].UniqueID)%>
<%= Html.HiddenFor(i=> i[counter].ImagePath) %>
<%= Html.CheckBoxFor(i => i[counter].IsSelected)%>
<img src="<%= Model.ElementAt(counter).ImagePath %>" alt="Image" width="128" height="128" />
</div>
<% } %>
<input id="Submit1" type="submit" value="submit" />
答案 0 :(得分:0)
http://blog.stevensanderson.com/2010/01/28/editing-a-variable-length-list-aspnet-mvc-2-style/为您所寻找的内容提供了解决方案。
或者,更简单但不太灵活的解决方案是将Room.cshtml文件和Option.cshtml文件放在Shared / EditorTemplates文件夹中。那你就放
<%= Html.TextBoxFor(m=> m.Name) %>
<% Html.EditorFor(m => m.Options); %>
Room.cshtml中的
<% Html.EditorFor(m => Model); %>
索引中的,以及Option.cshtml中部分视图的内容。