1

I want to return to same page with error message along with query string when the model is invalid in post operation

My code is here

public ActionResult Action1(string Key)
{

    // do something
}

[HttpPost]
public ActionResult Action1(Model user)
{
    if (ModelState.IsValid)
                {
    // do some stuff here
    }
    else
     // redirect to same page with query string key and also error message
}

Please suggest the line I need to add when the model is invalid to stay in the same page by showing the error message.

1

2 Answers 2

3
public ActionResult Action1(Model user)
{
    if (ModelState.IsValid)
    {
       // all is okay
    }
    // If we got this far, something failed, redisplay form
    ModelState.AddModelError("", "The user name or password provided is incorrect.");
    return View(model);
}
Sign up to request clarification or add additional context in comments.

Comments

2
[HttpPost]
public ActionResult Action1(Model user)
{
    if (ModelState.IsValid)
    {
    // do some stuff here
    }
    else
    {
        return this.RedirectToAction ("Action1", new { value1 = "QueryStringValue" });
    }
}

That would return this :

/controller/Action1?value1=QueryStringValue

Also as per your comment.
You can use below approach for model instead of sending errors from controller to view for model failing.

    [Required]
    [DataType(DataType.Text)]
    [StringLength(40)]
    public string FirstName { get; set; }

    [Required]
    [DataType(DataType.Text)]
    [EmailAddress]
    public string Email { get; set; }

    [Required]
    [DataType(DataType.Password)]
    [StringLength(1000, MinimumLength = 8)]
    public string Password { get; set; }

    [Required]
    [System.Web.Mvc.Compare("Password")]
    [DataType(DataType.Password)]
    public string PasswordConfirmation { get; set; }

3 Comments

But here the error messages are not showing, this is equal to RedirectToAction(), I need view()
Sorry I didn't get you. What do you mean by not getting error messages?
If the model is invalid, I can show some error message like length should be more than 6 or the password and confirm password do not match, it is not showing

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.