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的新手,所以我正在寻求其他人的意见。