我有一个带有Index方法的控制器,该方法有几个可选参数,用于过滤返回到视图的结果.
public ActionResult Index(string searchString, string location, string status) {
...
product = repository.GetProducts(string searchString, string location, string status);
return View(product);
}
Run Code Online (Sandbox Code Playgroud)
我想像下面这样实现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);
}
Run Code Online (Sandbox Code Playgroud)
我的理解是,如果出现以下情况,则不应使用此模式:
我应该尝试使用这种模式吗?如果是这样,我该怎么做呢?
谢谢!
PRG代表重定向后 - 获取.这意味着当您向服务器发回一些数据时,您应该重定向到一个GETAction.
为什么我们需要这样做?
想象一下,如果您有表格,您可以在其中输入客户注册信息,然后单击提交到HttpPost操作方法的提交位置.您正在从表单中读取数据并将其保存到数据库,而您没有进行重定向.相反,你会留在同一页面上.现在,如果您刷新浏览器(只需按F5按钮)浏览器将再次执行类似的表单发布,您的HttpPost Action方法将再次执行相同的操作.即; 它将再次保存相同的表单数据.这是个问题.为了避免这个问题,我们使用PRG模式.
在PRG中,您单击"提交"," HttpPost操作"方法将保存您的数据(或任何必须执行的操作),然后执行重定向到Get请求.因此,浏览器将向Get该Action 发送请求
RedirectToActionmethod返回HTTP 302对浏览器的响应,这会导致浏览器对指定的操作发出GET请求.
[HttpPost]
public ActionResult SaveCustemer(string name,string age)
{
//Save the customer here
return RedirectToAction("CustomerList");
}
Run Code Online (Sandbox Code Playgroud)
上面的代码将保存数据并重定向到Customer List操作方法.所以你的浏览器网址现在就可以了http://yourdomain/yourcontroller/CustomerList.现在,如果您刷新浏览器.IT部门不会保存重复数据.它只会加载CustomerList页面.
在搜索Action方法中,您不需要重定向到Get Action.您在products变量中有搜索结果.只需将其传递到所需视图即可显示结果.您不必担心重复的表单发布.所以你很擅长.
[HttpPost]
public ActionResult Index(ViewModel model) {
if (ModelState.IsValid) {
var products = repository.GetProducts(model);
return View(products)
}
return View(model);
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1363 次 |
| 最近记录: |