ASP.NET MVC 4 - 登录主页



我想在我的主页上有一个登录表单。index.cshtml我有这个:

@using (Html.BeginForm("Login", "AccountController", FormMethod.Post)) {
    @Html.AntiForgeryToken()
    @Html.ValidationSummary(true)
        <div>
            <div class="usernametb">
                @Html.LabelFor(m => m.LoginMod.UserName)
            </div>
            <div class="usernametb">
                @Html.TextBoxFor(m => m.LoginMod.UserName, new { style = "width:150px" })
                @Html.ValidationMessageFor(m => m.LoginMod.UserName)
            </div>
        </div>
        <div class="clear"></div>
        <div>
            <div class="pwtb">
                @Html.LabelFor(m => m.LoginMod.Password)
            </div>
            <div class="pwtb">
                @Html.PasswordFor(m => m.LoginMod.Password, new { style = "width:150px" })
                @Html.ValidationMessageFor(m => m.LoginMod.Password)
            </div>
        </div>
        <div class="clear"></div>
        <div class="rememberme">
            @Html.CheckBoxFor(m => m.LoginMod.RememberMe)
            @Html.LabelFor(m => m.LoginMod.RememberMe, new { @class = "checkbox" })
        </div>
        <div><input class="loginbutton" type="submit" value="Log In" /></div>
}

我参考这个模型:

namespace memsite.Models
{
    public class MemEvent
    {
        public LoginModel LoginMod { get; set; }
        public DateTime Start { get; set; }
        public DateTime End { get; set; }
        public string Name { get; set; }
        public string Description { get; set; }
    }
}

我正在尝试点击此帐户控制器登录操作,但它从未命中控制器,它只是重定向到不存在的/AccountController/Login。此外,验证控件不起作用...

namespace memsite.Controllers
{
    [Authorize]
    [InitializeSimpleMembership]
    public class AccountController : Controller
    {
        //
        // GET: /Account/Login
        [AllowAnonymous]
        public ActionResult Login(string returnUrl)
        {
            ViewBag.ReturnUrl = returnUrl;
            return View();
        }
        //
        // POST: /Account/Login
        [HttpPost]
        [AllowAnonymous]
        [ValidateAntiForgeryToken]
        public ActionResult Login(LoginModel model, string returnUrl)
        {
            if (ModelState.IsValid && WebSecurity.Login(model.UserName, model.Password, persistCookie: model.RememberMe))
            {
                return RedirectToLocal(returnUrl);
            }
            // If we got this far, something failed, redisplay form
            ModelState.AddModelError("", "The user name or password provided is incorrect.");
            return View(model);
        }

(我是MVC的新手,永远离开了网络表单的土地。

在窗体中使用帐户而不是帐户控制器。 ASP MVC 基于命名约定,并且隐含了控制器。

在下面一行中更改控制器的名称

@using (Html.BeginForm("Login", "AccountController", FormMethod.Post)) {

@using (Html.BeginForm("Login", "Account", FormMethod.Post)) { 

因为 ASP.NET MVC将通过路由配置自动检测以控制器结尾的任何内容

Web.config中的身份验证部分指定您具有登录类型:

<authentication mode="Forms">
    <forms loginUrl="Account/Login" timeout="2880" />
</authentication>

也许您的Web.config配置错误。

最新更新