我有家庭控制器动作,如:
public ActionResult Index()
{
ViewBag.Message = "Modify this template to jump-start your ASP.NET MVC application.";
List<SelectListItem> oList = new List<SelectListItem>();
oList.Add(new SelectListItem() { Text = "Rest1", Value = "1" });
oList.Add(new SelectListItem() { Text = "Rest2", Value = "2", Selected=true});
oList.Add(new SelectListItem() { Text = "Rest3", Value = "3" });
Person p = new Person() { PossibleSchools = oList };
return View(p);
}
在提交按钮单击时调用的另一个是::
public void ModelBinding(Person p)
{
var name = p.Name;
}
在视图中我有以下代码::
<div class="content-wrapper">
<hgroup class="title">
<h1>@ViewBag.Title.</h1>
<h2>@ViewBag.Message</h2>
</hgroup>
<form action="Home/ModelBinding" method="post">
<p>
Name :: <input type="text" name="Name"/>
Restaurant :: @Html.DropDownList("PossibleSchools");
<input type="submit" />
</p>
</form>
</div>
我的模特是::
public class Person
{
public string Name { get; set; }
public List<SelectListItem> PossibleSchools { get; set; }
}
问题在于,每当我尝试调试此应用程序时,我都会看到Name字段已绑定但PossibleSchools计数为零。
因此dropdownlist没有受到约束。
答案 0 :(得分:0)
在第一行视图中使用以下代码:
@model Person
<div class="content-wrapper">
<hgroup class="title">
<h1>@ViewBag.Title.</h1>
<h2>@ViewBag.Message</h2>
</hgroup>
<form action="Home/ModelBinding" method="post">
<p>
Name :: <input type="text" name="Name"/>
Restaurant :: @Html.DropDownListFor(model => model.Name, Model.PossibleSchools)
<input type="submit" />
</p>
</form>
</div>
答案 1 :(得分:0)
这是一个可能有帮助的重构版本:
在您的控制器中:
public ActionResult Index()
{
ViewBag.Message = "Modify this template to jump-start your ASP.NET MVC application.";
Person p = new Person();
return View(p);
}
public void ModelBinding(Person p)
{
// Perform action to process the request
}
你的模特:
public class Person
{
public string Name { get; set; }
public string SchoolName { get; set; }
public List<SelectListItem> PossibleSchools
{
get
{
return new List<SelectListItem>()
{
new SelectListItem() { Text = "Rest1", Value = "1" }),
new SelectListItem() { Text = "Rest2", Value = "2" }),
new SelectListItem() { Text = "Rest3", Value = "3" })
};
}
}
}
最后在你看来:
@model Person
<div class="content-wrapper">
<hgroup class="title">
<h1>@ViewBag.Title.</h1>
<h2>@ViewBag.Message</h2>
</hgroup>
<form action="Home/ModelBinding" method="post">
<p>
Name :: @Html.TextBoxFor(m => m.Name)
Restaurant :: @Html.DropDownListFor(model => model.SchoolName, Model.PossibleSchools)
<input type="submit" />
</p>
</form>
</div>
希望这有帮助。