Nathan McKaskle Nathan McKaskle - 1 year ago 176
C# Question

Model State Is Not Valid But Why?

I am getting a return to view when submitting POST on the Create page and debugging has narrowed it down to the model state not being valid, but I'm not sure why it isn't valid.

Here's what I am trying to do. I added a file to upload which was working fine in the create method until I needed to add more details from a dropdown menu. Originally it looked like this when all I needed was the file:

public ActionResult Create(HttpPostedFileBase file)
{
ViewBag.EnvironmentTypeId = new SelectList(db.environmenttypes, "EnvironmentTypeId", "EnvironmentTypeName", 1);
if (ModelState.IsValid)
{
IO io = new IO();
if (file != null)
{
AppUpdate updateLog = io.UpdateApp(file, env.EnvironmentTypeId);
updateLog.UserName = User.Identity.Name;
updateLog.EnvironmentTypeId = env.EnvironmentTypeId;
db.appupdates.Add(updateLog);
db.SaveChanges();
}
else
{
return RedirectToAction("Create");
}
return RedirectToAction("Index");
}

return View();
}


So I added more to the model to get details:

public ActionResult Create([Bind(Include="EnvironmentTypeId")] AppUpdate env, HttpPostedFileBase file)
{
ViewBag.EnvironmentTypeId = new SelectList(db.environmenttypes, "EnvironmentTypeId", "EnvironmentTypeName", 1);
if (ModelState.IsValid)
{
IO io = new IO();
if (file != null)
{
AppUpdate updateLog = io.UpdateApp(file, env.EnvironmentTypeId);
updateLog.UserName = User.Identity.Name;
updateLog.EnvironmentTypeId = env.EnvironmentTypeId;
db.appupdates.Add(updateLog);
db.SaveChanges();
}
else
{
return RedirectToAction("Create");
}
return RedirectToAction("Index");
}

return View();
}


Why is it invalid here? What's wrong with it? Let me know first please if I'm missing more details that I haven't added before marking it down.

Answer Source

ModelState has a property that will tell you exactly why it's not valid. Use that.

Here's an answer with an example: Get error message if ModelState.IsValid fails?

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download