cp100
cp100

Reputation: 1503

Query string parameters get removed after do the post and return to the same page in asp.net mvc

I'm implementing an asp.net mvc5 application and having an issue with post operation and query string parameters.

My page url is http://localhost/site/person/edit?personId=20

[HttpGet]
public ActionResult Edit(int personID)
{
    // ....   

    return View(person);
}

In this page contain submit button and it will do the post method. In post method, if Model.Isvalid get false, I return to the view with Model.

[HttpPost]
public ActionResult Edit(Person person)
{
    if (ModelState.IsValid)
    {
          //....
          return RedirectToAction("Index", "Dashboard", new { area = "" });
    }
    else
    {
          return View(person);
    }
}

This works correctly. But the issue is once the Model.IsValid get false, it will come to the view but with no query string parameters. Then URL is like http://localhost/site/person/edit

Is there a way to get the URL with query string parameters.

Upvotes: 4

Views: 3636

Answers (3)

Ralph Hinkley
Ralph Hinkley

Reputation: 390

I found the answer on another SO post: Query string param is missed when form validation fail

The solution for me was to concatenate the dropped value directly onto the form tag.

Using the BeginForm() method:

@using (Html.BeginForm("Edit", "Person", routeValues: new {personID = Model.id}, method: FormMethod.Post))

Upvotes: 9

SilverlightFox
SilverlightFox

Reputation: 33578

Add your ID to the POST method also:

[HttpPost]
public ActionResult Edit(int personID, Person person)
{
    if (ModelState.IsValid)
    {
          //....
          return RedirectToAction("Index", "Dashboard", new { area = "" });
    }
    else
    {
          return View(person);
    }
}

Your view should also POST to the same URL as it is on:

  @using (Html.BeginForm())

Upvotes: 1

spender
spender

Reputation: 120518

Yes. Don't supply (200 OK) content in answer to a POST, but redirect with a query string to a GET method.

Supplying content in a POST is almost always a bad idea because when the user refreshes the page, the POST gets made again (along with a confusing dialog in many users agents that asks the user if they are sure the want to resend the POST)

Upvotes: 2

Related Questions