我有一个登录表单,如果用户输入正确的登录信息,他/她将进入我的网站。
但是,如果他/她输入的信息不正确,我希望将他返回到他/她已经提交的字段输入他/她信息的页面。
我的意思是,我希望他能够看到他/她在字段中输入的用户名和密码的页面,而不是从零开始输入。
我试过了
public ActionResult(Login ?login = null){}
所以我想在显示带有null参数的登录页面时调用此函数。当用户输入不正确的信息时我会调用它。但是,我去了例外
你能解决这个问题吗?“Login”类型必须是非可空值类型才能在泛型类型或方法'System.Nullable'中将其用作参数'T'
当用户按下登录按钮时,我转到此控制器功能
public ActionResult Index()
{
return View();
}
当他在登录页面提交他/她的表格时,我会转到此功能
public ActionResult Login(Login login) {}
我想在上面的login
函数中,如果用户输入的信息不正确,无法返回到他/她看到他/她提交的数据的index
页面
答案 0 :(得分:2)
创建一个新的MVC Internet应用程序(VS模板),并查看如何在控制器内部使用“Model.IsValid”。这是最常用的方法。当一些模型进入控制器时,你检查它是否有效(重定向到主页或其他),否则你只是显示相同的视图,为它提供已经(部分)由用户弹出的模型。
这是一个:
[HttpPost]
public ActionResult LogOn(LogOnModel model, string returnUrl)
{
if (ModelState.IsValid)
{
// do things
return RedirectToAction("Index", "Home");
}
// If we got this far, something failed, redisplay form
return View(model);
}
模型错误可能在隐式模型绑定期间发生(例如,如果传入数据中不存在某些必需属性),或者通过使用ModelState.AddModelError在代码中显式设置。在页面上放置html验证器可以让用户知道对字段值应用了哪种约束。
答案 1 :(得分:1)
你只需使用它:
// [HttpPost] and any other attributes necessary
public ActionResult YourAction(Login login)
{
...
}
但是考虑到你想要实现的逻辑的一般概念,我会说你不需要登录为null。
该操作只是执行它的操作:它处理登录(在客户端部分完成回发之后)。因此,它始终必须包含任何数据。
如果您希望在对登录信息进行一些检查后重定向,则会收到它们,检查然后执行RedirectToAction(...)
或任何其他类型的重定向。
然后在视图中你会(例如对于Index动作):
@model Login
@using(Html.BeginForm("YourAction", "home"))
{
@Html.LabelFor(model => model.UserName)
@Html.TextBoxFor(model => model.UserName)
@Html.ValidationMessageFor(model => model.UserName)
@Html.LabelFor(model => model.Password)
@Html.PasswordFor(model => model.Password)
@Html.ValidationMessageFor(model => model.Password)
<input type="submit" value="go"/>
}
修改强>
想象一下你的YourAction是登录:
[HttpGet]
public ActionResult Login()
{
// this one is called on the first entering of login and shows the form to fill
return View(new Login()); // for instance
}
[HttpPost]
public ActionResult Login(Login login)
{
// this one is called on PostBack after filling the form and pressing 'Login' (or something) button
// todo: here you to validate the login info
// and then either do your redirect to some other page or showing the login form again
// if(something)
// return RedirectToAction(...);
return View(login);
}