【问题标题】:post data with different action name but url doesn't change使用不同的操作名称发布数据,但 url 不会改变
【发布时间】:2018-12-16 16:52:47
【问题描述】:

我有一个带有搜索功能的索引页面来显示数据。输入条件(或没有条件)后,我使用 POST 方法将请求提交到不同的操作名称(搜索操作),但结果将返回到索引视图。

Index.cshtml

@using (Html.BeginForm("Search", "Home"))
{
    // criteria fields
    <button type="submit" class="btn btn-primary">Search</button>
}

HomeController.cs

public ActionResult Index()
{
    // preparing the view model
    return View();
}

[HttpPost]
public ActionResult Search(HomeViewModel vm)
{
    // get the data
    return View("Index", vm);
}

这会将网址更改为我不想显示的http://localhost:12345/Home/Search。我可以将 Search 操作名称更改为 Index,因此 get 和 post 请求将使用相同的名称,但是有什么方法可以使 url 不变?

我尝试在 RouteConfig.cs 中添加新路由

routes.MapRoute(
    name: "Search",
    url: "",
    defaults: new { controller = "Home", action = "Search" }
);

但它不起作用,我遇到了 404 错误。

【问题讨论】:

    标签: asp.net-mvc url-routing asp.net-mvc-routing


    【解决方案1】:

    目前您正在遵循默认实现。意味着当您发布数据时,它将提交表单到发布方法,这是正确的。这两种方法都可以解决。

    1. 使用 ajax 发布到 Url,这样它就不会更改浏览器中的 Url。

    2. 使用重定向到索引。

        public ActionResult Index()
          {
              if(Session["IndexVM"] != null)
                    return View((HomeViewModel )Session["IndexVM"]);
              return View();
          }
          [HttpPost]
          public ActionResult Search(HomeViewModel vm)
          {
              // your search code
              Session["IndexVM"] = vm;
              return RedirectToAction("Index");
          }
      

    【讨论】:

    • 感谢您的回答。首先,如果我更改为 ajax,则需要很长时间,因为我还必须更改分页和排序,所以我使用第二个选项并使用 TempData。顺便说一句,这可以通过在 RouteConfig.cs 中添加路由来完成吗?
    • 路由用于传入请求而不是传出请求。在您的情况下,当您第一次显示时,它是索引,当您发布它时,它将发布到 Search 方法并且您正在返回视图,因此它可以是任何视图,但它不会影响 url。在这种情况下,路线没有帮助。现在 tempdata 或 Session 由您决定。 TempData 是 Session 之上的一层。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-01-05
    • 2016-09-22
    • 1970-01-01
    • 2021-05-29
    • 1970-01-01
    • 2021-04-23
    相关资源
    最近更新 更多