2015-04-07 31 views
0

在下面的代码片段中,您会用什么来代替TempData以实现相同的预期结果 - 在无效的ModelState情况下重定向并传递登录错误?如何在不使用TempData的情况下实现相同的结果

public ActionResult Welcome(string returnUrl, int accountTypeId = 0) 
    { 
     //this is logic from the original login page. not sure if this would ever occur. we may be able to remove this. 
     if (string.IsNullOrEmpty(returnUrl) == false && returnUrl.Contains("?route=")) 
     { 
      var split = returnUrl.Split(new[] {"?route="}, StringSplitOptions.None); 
      var route = Server.UrlDecode(split[1]); 
      returnUrl = split[0] + "#" + route; 
     } 

     object model; 
     if (TempData.TryGetValue("LogOnModel", out model) == false) 
     { 
      model = new LogOnModel 
      { 
       ReturnUrl = returnUrl, 
       AccountTypeId = accountTypeId 
      }; 
     } 

     object errors; 
     if (TempData.TryGetValue("Errors", out errors)) 
     { 
      ModelState.Merge(errors as ModelStateDictionary); 
     } 

     return View(model); 
    } 

    [HttpPost] 
    [ValidateAntiForgeryToken] 
    public ActionResult Welcome(LogOnModel model) 
    { 
     Func<ActionResult> invalid =() => 
     { 
      TempData.Add("Errors", ModelState); 
      TempData.Add("LogOnModel", model); 
      return RedirectToAction("Welcome"); 
     }; 

     if (ModelState.IsValid == false) 
     { 
      return invalid(); 
     } 

正如目前的情况是,如果用户点击后退按钮和尝试登录在第二时间代码创建一个错误。错误消息“具有相同密钥的项目已被输入”我试图避免此错误。我尝试在TempData的地方使用ViewData,但是在有人输入错误密码的情况下,这打破了我的登录错误消息。我是MVC的新手,所以我正在寻求其他人的意见。

回答

0

它看起来并不像你正在做的任何Ajax,所以你不需要在这种情况下重定向错误。当模型状态无效时,您会为您填充称为模型状态错误的集合。您只需要再次返回欢迎页面并将@ Html.ValidationSummary添加到欢迎页面cshtml。

Html.ValidationSummary读取模型状态错误,然后确定是否需要显示错误框。这是我会做的。

[HttpPost] 
[ValidateAntiForgeryToken] 
public ActionResult Welcome(LogOnModel model) 
{ 
    if (ModelState.IsValid == false) 
    {//We have model state errors populated here for us 
     return View(model); 
    } 
    //Do Work 
} 
相关问题