1

Have created a model and with required fields and used to create a form like so:

Model:

public class formModel {
    [Required]
    public string name {get;set;}
    [Required]
    public string Add1 {get;set;}
    etc....
}

View:

@model myProj.Models.formModel

@using (BeginForm("Action", "Controller", FormMethod.Post))
{
    @Html.TextBoxFor(f => f.name)
    @Html.TextBoxFor(f => f.Add1)
    etc...

    @Html.ValidationSummary()
    <button type="submit" value="submit">Submit</button>
}

Controller:

[HttpPost]
public ActionResult Action(formModel f)
{
    if (ModelState.IsValid)
    {
        // Do Stuff here
        return RedirectToAction("Result");
    }
    return RedirectToAction("Form", new { id = "showForm" });
 }

Problem is the validation summary is being displayed if the model is in valid. Have used same approach on lots of other forms and has been fine.

Any ideas?

1 Answer 1

5

When the model is invalid, do not use

return RedirectToAction("Form");

But

return View(f); // or return View("ViewName", f);
Sign up to request clarification or add additional context in comments.

2 Comments

Unfortunately the form is in a partial view and the name of the action doesn't relate directly the name of the views. The form only gets shown when the correct ID is added onto the end of the Action in the url. Have edited original code.
Remember that the modelstate is not stored in the TempData or something, so after a redirect it is gone and so are the validation messages. When you use forms in a partial that are shown on certain conditions, or multiple forms on a page, consider using an AJAX approach.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.