1

我有一个登录表单,如果用户输入正确的登录信息,他/她将进入我的网站。

但是,如果他/她输入的信息不正确,我想将他/她返回到他/她输入他/她的信息以及已经提交的字段的同一页面。

我的意思是,我想在他/她可以看到他/她在字段中输入的用户名和密码的页面上,而不是从零开始输入。

我试过了

public ActionResult(Login ?login = null){}

所以当我想显示带有空参数的登录页面时,我调用了这个函数。当用户输入不正确的信息时,我会调用它。但是,我去例外

类型“Login”必须是不可为空的值类型,才能将其用作泛型类型或方法“System.Nullable”中的参数“T”

你帮我解决这个问题好吗?

如果有第二种解决方案告诉我,但请不要谈论会员和这些人,因为我有自己的方式来向用户保证

编辑

当用户按下登录按钮时,我转到此控制器功能

public ActionResult Index()
        {
            return View();
        }

当他在登录页面提交他/她的表单时,我会转到此功能

public ActionResult Login(Login login) {}

我想在上面的login函数中,如果用户输入不正确的信息返回到index他/她看到他/她提交的数据的页面

4

2 回答 2

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 验证器可以让用户知道对字段值应用了什么样的约束。

于 2013-11-09T23:27:31.280 回答
1

你只需使用这个:

// [HttpPost] and any other attributes necessary
public ActionResult YourAction(Login login)
{
    ...
}

但是考虑到您想要实现的逻辑的一般概念,我会说您不需要登录为空。

该操作只是做它做的事情:它处理登录(在客户端部分完成回发之后)。因此,它始终必须包含任何数据。

如果您想在对登录信息进行一些检查后重定向,您会收到它们,检查然后执行RedirectToAction(...)或您想要的任何其他类型的重定向。

然后在视图中您将拥有(例如,对于索引操作):

@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 是 Login:

[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);
}
于 2013-11-09T23:27:07.273 回答