查询字符串参数被删除后做的帖子,并返回到同一页在asp.net mvc

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

本文关键字:返回 一页 mvc net asp 参数 字符串 删除 查询      更新时间:2023-09-26

我正在实现asp.net mvc5应用程序,并且有一个post操作和查询字符串参数的问题。

我的网页url是http://localhost/site/person/edit?personId=20

[HttpGet]
public ActionResult Edit(int personID)
{
    // ....   
    return View(person);
}

在这个页面包含提交按钮,它将做post方法。在post方法中,如果Model。Isvalid = false,则返回Model。

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

可以正常工作。但问题是一旦模型。IsValid = false,它将进入视图,但不带查询字符串参数。URL是http://localhost/site/person/edit

是否有办法获得URL与查询字符串参数

我在另一个帖子上找到了答案:表单验证失败时缺少查询字符串参数

我的解决方案是将删除的值直接连接到表单标记上。

使用BeginForm()方法:

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

是。不要在回复POST时提供(200 OK)内容,而是用查询字符串重定向到GET方法。

在POST中提供内容几乎总是一个坏主意,因为当用户刷新页面时,POST会再次生成(同时在许多用户代理中会出现一个令人困惑的对话框,询问用户是否确定要重新发送POST)

将ID也添加到POST方法中:

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

你的视图也应该POST到相同的URL,因为它在:

  @using (Html.BeginForm())