I have one simple page mvc with one action. Get method in the index action I create an instance of the property model.categoria and I value with 3 items. The problem is that if I run the post index of action, as you can see below, I have an error because the dropdownlist associated model.categoria is null. My question is: I always instantiated at every post the model.categoria order to avoid this problem, one that today I wonder, is rightly so?
Here is the code that I will return an error: Value cannot be null.
controller action:
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);
}
index.cshtml
@Html.LabelFor(x => x.categoria)
@Html.DropDownListFor(x => x.categoria.First().idCategoria, new SelectList(Model.categoria, "idCategoria", "TitoloCategoria"))
You do have to populate the list every time you do a post back unless you were to put hidden field for all of the values in your form. It only takes a few lines of code though to make this work a different way
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 });
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.