- HTTP Post request from different controller actions and ModelState
- public class ProductController : Controller {
- [HttpPost]
- public ActionResult Search(SearchModel searchModel) {
- if (ModelState.IsValid) {
- //Do some stuff...
- return RedirectToAction("Index", "SearchResult");
- }
- return View(searchModel);
- }
- }
- public class SearchModel {
- [Required]
- public string ProductCategory { get; set; }
- [Required]
- public string ProductName { get; set; }
- }
- @model MvcApplication20.SearchModel
- @using (Html.BeginForm("search", "product"))
- {
- @Html.EditorForModel()
- <input type="submit" value="Search" />
- }
- @{
- ViewBag.Title = "Home Page";
- }
- <h2>@ViewBag.Message</h2>
- @Html.Partial("_SearchPartialView")
- [HttpPost]
- public ActionResult Search(SearchModel searchModel) {
- if (ModelState.IsValid) {
- //Do some stuff...
- return RedirectToAction("Index", "SearchResult");
- }
- // since we are returning a view instead of a partial view,
- // the _SearchPartialView template should be displayed with the layout
- return View("_SearchPartialView", searchModel);
- }
- $(document).on('submit', '#searchForm', function() {
- $.ajax({
- url: this.action,
- type: this.method,
- data: $(this).serialize(),
- success: function(result) {
- if (result.redirectTo) {
- // no validation errors we can redirect now:
- window.location.href = result.redirectTo;
- } else {
- // there were validation errors, refresh the partial to show them
- $('#searchContainer').html(result);
- // if you want to enable client side validation
- // with jquery unobtrusive validate for this search form
- // don't forget to call the .parse method here
- // since we are updating the DOM dynamically and we
- // need to reattach client side validators to the new elements:
- // $.validator.unobtrusive.parse(result);
- }
- }
- });
- return false;
- });
- <div id="searchContainer">
- @Html.Partial("_SearchPartialView")
- </div>
- [HttpPost]
- public ActionResult Search(SearchModel searchModel) {
- if (ModelState.IsValid) {
- //Do some stuff...
- return Json(new { redirectTo = Url.Action("Index", "SearchResult") });
- }
- return PartialView("_SearchPartialView", searchModel);
- }