我无法理解为什么我的SelectListItem
以null发布。这是我的情景:
public class MyViewModel
{
public int SelectedCategoryId {get;set;
public IList<Category> Categories {get;set}
public IList<SelectListItem> CategoriesSelectListItem
{
get
{
var list = (from item in Categories
select new SelectListItem()
{
Text = item.Name,
Value = item.Id.ToString()
}).ToList();
return list;
}
set { }
}
}
[HttpGet]
public ActionResult Index()
{
IList<Category> categs = repository.GetCategories();
return View(new MyViewModel(){ Categories = categs });
}
[HttpPost]
public ActionResult Index(MyViewModel model) // At this point model.Categories is null on postback
{
if(ModelState.IsValid())
{
// Do some Logic
return Content("Succes!");
}
return View(model); //Throw again the view if model state is not valid
}
观点:
@model MyViewModel
@{
Layout=null;
}
@Html.DropDownListFor(x => x.SelectedCategoryId,Model.CategoriesSelectListItem)
那么如何在Model.Categories WHITHOUT ViewData[""]
或Session
变量上保持绑定?
谢谢!
添加了视图
答案 0 :(得分:0)
当您发布表单时,您发布的信息是input
字段中的信息。
因为,你有一个DropDownList
的模型属性SelectedCategoryId
(我想它在一个Form块中),唯一要发布的字段是选中的值。
这就是HTTP和Asp.Net MVC3中的工作方式。可能是你来自普通的ASP.NET,其中所有页面都被传送(发布)到服务器,你会感到困惑。
我们通常只需要选定的值,因为在每个请求中都会从数据库中检索完整的下拉列表(或缓存以避免多次访问数据库)。如果你考虑一下,你想知道用户选择了什么,你向他显示的列表就已经知道了。