MVC3:具有操作方法搜索筛选器的 PRG 模式



>我有一个带有 Index 方法的控制器,该方法有几个可选参数,用于筛选返回到视图的结果。

public ActionResult Index(string searchString, string location, string status) {
    ...
product = repository.GetProducts(string searchString, string location, string status);
return View(product);
}

我想像下面这样实现 PRG 模式,但我不确定如何去做。

[HttpPost]
public ActionResult Index(ViewModel model) {
    ...
    if (ModelState.IsValid) {
        product = repository.GetProducts(model);
    return RedirectToAction(); // Not sure how to handle the redirect
    }
return View(model);
}

我的理解是,在以下情况下,您不应使用此模式:

  • 除非你实际存储了一些数据,否则你不需要使用此模式(我不是(
  • 刷新页面时,您不会使用此模式来避免来自 IE 的"您确定要重新提交"消息(有罪(

我应该尝试使用此模式吗?如果是这样,我将如何去做?

谢谢!

prg 代表 post-redirect-get。 这意味着当您将一些数据发布到服务器时,您应该重定向到GET操作。

为什么我们需要这样做?

假设您有表单,您可以在其中输入客户注册信息,然后单击提交,将其发布到 HttpPost 操作方法。您正在从表单中读取数据并将其保存到数据库,并且没有执行重定向。相反,您停留在同一页面上。现在,如果您刷新浏览器(只需按F5按钮(,浏览器将再次执行类似的表单发布,并且您的HttpPost操作方法将再次执行相同的操作。小它将再次保存相同的表单数据。这是一个问题。为了避免这个问题,我们使用PRG模式。

PRG中,您单击提交,HttpPost操作方法将保存您的数据(或它必须执行的任何操作(,然后执行重定向到Get请求。因此,浏览器将向该操作发送Get请求

RedirectToAction 方法向浏览器返回HTTP 302响应,这会导致浏览器向指定的操作发出 GET 请求。

[HttpPost]
public ActionResult SaveCustemer(string name,string age)
{
   //Save the customer here
  return RedirectToAction("CustomerList");
}

上面的代码将保存数据并重定向到客户列表操作方法。因此,您的浏览器网址现在将http://yourdomain/yourcontroller/CustomerList。现在,如果您刷新浏览器。IT 不会保存重复的数据。它将简单地加载客户列表页面。

在搜索操作方法中,无需执行重定向到获取操作。搜索结果位于products变量中。只需将其传递给所需的视图即可显示结果。您无需担心重复的表单发布。所以你对此很满意。

[HttpPost]
public ActionResult Index(ViewModel model) {
    if (ModelState.IsValid) {
        var products = repository.GetProducts(model);
        return View(products)
    }
  return View(model);
}

重定向只是一个操作结果,它是另一个操作。因此,如果您有一个名为"搜索结果"的操作,您只需说

return RedirectToAction("SearchResults");

如果操作在另一个控制器中...

return RedirectToAction("SearchResults", "ControllerName");

带参数...

return RedirectToAction("SearchResults", "ControllerName", new { parameterName = model.PropertyName });

更新

我突然想到您可能还希望选择将复杂对象发送到下一个操作,在这种情况下,您的选择有限,TempData 是首选方法

使用您的方法

[HttpPost]
public ActionResult Index(ViewModel model) {
    ...
    if (ModelState.IsValid) {
        product = repository.GetProducts(model);
        TempData["Product"] = product;
        return RedirectToAction("NextAction");
    }
    return View(model);
}
public ActionResult NextAction() {
    var model = new Product();
    if(TempData["Product"] != null)
       model = (Product)TempData["Product"];
    Return View(model);
}

最新更新