我有一个简单的页面 mvc,只有一个操作。
在索引操作中的 Get 方法中,我创建了属性 model.categoria 的实例,并使用 3 个项目进行值。
问题是,如果我运行操作的后索引(如下所示),则会出现错误,因为与 model.categoria 关联的下拉列表为空。
我的问题是:
我总是在每一篇文章中实例化 model.categoria 以避免这个问题,今天我想知道,是这样吗?
这是我将返回错误的代码:
值不能为空。
控制器动作:
public ActionResult Index()
{
var model = new Models.UploadVideoPage.UploadVideoPageModel();
model.categoria = new List<Models.UploadVideoPage.ListCategorie>();
model.categoria.Add(new ListCategorie { TitoloCategoria = "Volontariato", idCategoria = 1 });
model.categoria.Add(new ListCategorie { TitoloCategoria = "Interno", idCategoria = 2 });
model.categoria.Add(new ListCategorie { TitoloCategoria = "Sindacato", idCategoria = 3 });
return View(model);
}
[HttpPost]
public ActionResult Index(Models.UploadVideoPage.UploadVideoPageModel model)
{
return View(model);
}
索引.cshtml
@Html.LabelFor(x => x.categoria)
@Html.DropDownListFor(x => x.categoria.First().idCategoria, new SelectList(Model.categoria, "idCategoria", "TitoloCategoria"))
每次回发时都必须填充列表,除非您要为表单中的所有值放置隐藏字段。只需要几行代码就可以以不同的方式工作
public ActionResult Index()
{
var model = new Models.UploadVideoPage.UploadVideoPageModel();
PopulateDependencies(model);
return View(model);
}
[HttpPost]
public ActionResult Index(Models.UploadVideoPage.UploadVideoPageModel model)
{
PopulateDependencies(model);
return View(model);
}
private void PopulateDependencies(Models.UploadVideoPage.UploadVideoPageModel model)
{
model.categoria = new List<Models.UploadVideoPage.ListCategorie>();
model.categoria.Add(new ListCategorie { TitoloCategoria = "Volontariato", idCategoria = 1 });
model.categoria.Add(new ListCategorie { TitoloCategoria = "Interno", idCategoria = 2 });
model.categoria.Add(new ListCategorie { TitoloCategoria = "Sindacato", idCategoria = 3 });
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)