当我在asp.net mvc控制器操作中验证失败时,如何保留我的URL

leo*_*ora 5 c# asp.net-mvc

如果我从详细信息页面开始:

http:\\www.mysite.com\App\Detail
Run Code Online (Sandbox Code Playgroud)

我有一个名为Update的控制器操作,通常会将redirectToAction调用回详细信息页面.但我有一个错误,在验证中被捕获,我需要在重定向之前返回(以避免丢失我的所有ModelState).这是我的控制器代码:

 public override ActionResult Update(Application entity)
    {
        base.Update(entity);
        if (!ModelState.IsValid)
        {
            return View("Detail", GetAppViewModel(entity.Id));
        }
      return RedirectToAction("Detail", new { id = entity.Id }) 
Run Code Online (Sandbox Code Playgroud)

但现在我看到带有验证错误消息的视图(因为我正在使用HTML.ValidationSummary())但是url看起来像这样:

http:\\www.mysite.com\App\Update
Run Code Online (Sandbox Code Playgroud)

无论如何,我可以避免更改URL而没有将模型状态放入某些临时变量的黑客攻击?这里有一个最佳实践,因为我见过的唯一例子是在调用redirectToAction之间将ModelState放入一些tempdata中.

Bik*_*Lem 5

从ASP.NET MVC 2开始,没有任何此类API调用在return View()从另一个操作方法调用时维护原始操作方法的URL .

因此,推荐的解决方案和ASP.NET MVC中普遍接受的约定是具有仅接受HTTP POST动词的相应的,具有相似名称的动作方法.因此,在您的情况下,使用另一个名为Detaillike的操作方法可以解决您在验证失败时使用不同URL的问题.

[HttpPost]
public ActionResult Detail(Application entity)
{
    base.Update(entity);
    if (ModelState.IsValid)
    {
        //Save the entity here
    }
   return View("Detail", new { id = entity.Id });
}  
Run Code Online (Sandbox Code Playgroud)

此解决方案符合ASP.NET MVC最佳实践,并且还避免了使用modestatetempdate.

此外,如果您尚未探索此选项,那么asp.net mvc中的客户端验证可能也会针对您的URL问题提供一些解决方案.我强调一些,因为这种方法在浏览器上禁用javascript时不起作用.

因此,最好的解决方案是使用一个名为Detail但仅接受HTTP POST动词的动作方法.