ASP.NET Submitting Form - Status Code 302 Found

Viewed 1096

I have simple form. When i submit empty form (for testing validations) using a post request ...

It doesn't shows the validation messages and also return status Code 302. and also generate some random quesry string. something like this:

http://localhost:49852/Events/Create?Type=0&details=System.Collections.Generic.List%601%5BSampleProject.Models.Type%5D

This satuation i have never seen before!

@{Html.BeginForm("Save", "Event" , FormMethod.post);}

    @Html.ValidationSummary(true, "Please fix these problems.")

    // fields...
    <input type="submit" value="Save" class="btn btn-primary" />

@{Html.EndForm();}

Controller

[Authorize]
[HttpPost]
public ActionResult Save(EventFormViewModel viewModel)
{
    if (!ModelState.IsValid)
        return RedirectToAction("Save",viewModel);

    //..additional Code.

    return RedirectToAction("Index", "Home");
}
1 Answers

Problem is that, if ModelState is InValid you are redirecting to the Save method with model data instead of returning the current view with invalid model data.

So write your Save POST method as follows:

[Authorize]
[HttpPost]
public ActionResult Save(EventFormViewModel viewModel)
{
    if (!ModelState.IsValid)
        return View(viewModel);

    //..additional Code.

    return RedirectToAction("Index", "Home");
}
Related