I have a partial view that I’m using on my index page to display a form. When an item is selected from a dropdown menu on the index page, the partial view is loaded with corresponding form data. I need to validate the form when submitted, but I’m not sure what to return from my controller that will load the page correctly when displaying errors. My submit button is currently on my partial view. (I tried moving the submit to the Index page, but it did not return anything from the form.) If there are validation errors, the partial view loads, but the dropdown menu from the Index view does not. I’ve seen a few solutions to this issue but none have worked in this situation, probably due to the dropdown. Any help is greatly appreciated. Please let me know if the HTML would be helpful, I was having issues formatting it for this post.
Controller:
public class PrinterSettingsController : Controller
{
public ActionResult Index()
{
ViewBag.Areas = db.Areas.ToList();
PopulateDocumentTypeViewBag();
return View();
}
public ActionResult AreaDocumentSettingsList(int areaId = 0)
{
PopulateDocumentTypeViewBag();
//get area, contains list of document settings
}
return PartialView("_AreaDocumentSettingsList", selectedArea);
}
[HttpPost]
public ActionResult AreaDocumentSettingsList(Area selectedArea)
{
if (IsPrinterValid(selectedArea.PrinterName) == false)
{
ModelState.AddModelError(string.Empty, "Incorrect printer path entered.");
}
if (ModelState.IsValid)
{
//do some stuff, save the new records to the database
db.Entry(originalAreaRecord).CurrentValues.SetValues(selectedArea);
db.SaveChanges();
//if everything saves fine, go to a different page
return RedirectToAction("Index", "Workorder");
}
//if there are errors -- this part needs to be changed -- show errors in partial view, but also display view it's nested inside of
return View("_AreaDocumentSettingsList", selectedArea);
}
@cshemby’s link was helpful: Updating Partial Views with Unobtrusive AJAX in MVC 3
But my problem ended up being that I was loading my partial view into a
<div>tag with a javascript .changed event. In order to fix this, I added a@Html.RenderPartialto the Index page for the partial view and passed the value of the dropdown back to my controller instead. That way I could reload the entire page, including the validation.