I have a controller like this:
public FooController : Controller
{
public ActionResult Index()
{
return View();
}
}
With the Index view:
@{ Html.RenderPartial("~/Views/Bar/Add", new Models.Bar()); }
The Bar controller is like this:
public BarController : Controller
{
public ActionResult Add()
{
var bar = new Bar();
return View(bar);
}
[HttpPost]
public ActionResult Add(Bar bar)
{
if(ModelState.IsValid)
{
_repository.AddBar(bar);
return RedirectToAction("Index", "Foo");
}
// This will return only the partial view (No Layout, no outer view)
return View("Add", bar);
// This will not show validation errors
// return RedirectToAction("Index", "Foo");
}
}
And the Add View looks like this:
@model Models.Bar
@using(Html.BeginForm("Add", "Bar", FormMethod.Post))
{
Name: @Html.TextBoxFor(x => x.Name)
<input type="submit" value="Add Bar" />
@Html.ValidationSummary()
}
My problem is that if I return View("Add", bar) I get the partial view, and nothing else (not what I want). But if I instead return RedirectToAction("Index", "Foo") whether it passes validation or not, I of course lose any validation errors for the valiation summary.
Is there a way to use validation in a partial view like this?
You could:
return View("~/Views/Home/Index.cshtml")if validation fails.