我不明白为什么我的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、ViewData[""]或Session变量的情况下,如何在ViewData[""]上继续绑定呢?
谢谢!
更新1
添加了视图
发布于 2013-10-29 18:26:21
当您发布表单时,您要发布的信息是input字段中的信息。
因为,您有一个用于模型属性SelectedCategoryId的SelectedCategoryId(我想它在一个表单块中),所以唯一要发布的字段是选中的值。
HTTP和Asp.Net MVC3就是这样工作的。您可能来自普通的ASP.NET,在那里所有的页面都会被发送到服务器上,您会感到困惑。
我们通常只需要所选的值,因为在每个请求中都会从数据库中检索完整的下拉列表(或缓存以避免多次访问数据库)。如果你想一想,你想知道用户选择了什么,你向他显示的列表,你已经知道了。
https://stackoverflow.com/questions/19665613
复制相似问题