MVC 4 Post没有击中控制器/动作

时间:2015-04-13 21:25:58

标签: .net asp.net-mvc asp.net-mvc-4 post razor

我在MVC 4中遇到一个非常烦人的问题,我的表单帖子没有达到我指定的操作。我之前已经完成了这么多次并且工作正常但是在我的新项目中它似乎根本不起作用。

这是一个简单的登录页面,没有任何花哨,只是一个用户名和密码字段。这是我的代码

HTML /剃须刀:

@model XYZ.Models.PageModels.LoginPageModel

<div class="login">
    <form class="left form">
        @using (Html.BeginForm("Login", "Account", FormMethod.Post))
        {
            <div class="form-group form-group-sm">
                <label class="control-label" for="UserName">User Name</label>
                @Html.TextBoxFor(model => model.UserName, new {@class="form-control", @placeholder="User Name"})
            </div>


            <div class="form-group form-group-sm">
                <label class="control-label" for="Password">Password</label>
                @Html.PasswordFor(model => model.Password, new {@class="form-control", @placeholder="Password"})
            </div>


            <div class="buttons right">
                <input type="submit" class="btn btn-primary btn-sm" value="Login" />
            </div>
        }
    </form>
</div>

控制器:

public class AccountController : Controller
    {
        public ActionResult Login()
        {
            return View();
        }

        [HttpPost]
        public ActionResult Login(LoginPageModel model)
        {
            throw new Exception("I'm here!");
            return View();
        }
    }

路线配置:

routes.MapRoute(
                name: "Default",
                url: "{controller}/{action}/{id}",
                defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
            );

型号:

public class LoginPageModel
    {
        [Required(ErrorMessage = "User Name required")]
        public string UserName { get; set; }

        [Required(ErrorMessage = "Password required")]
        public string Password { get; set; }
    }

任何想法? 谢谢!

1 个答案:

答案 0 :(得分:7)

您在标记中嵌套了表单。你自己编写的,另一个是Html.BeginForm辅助方法生成的。摆脱外面的,你很高兴。

这应该可以正常工作。

<div class="login">
    @using (Html.BeginForm("Login", "Account"))
    {
        <div class="form-group form-group-sm">
            <label class="control-label" for="UserName">User Name</label>
            @Html.TextBoxFor(model => model.UserName, new { @class = "form-control", @placeholder = "User Name" })
        </div>


        <div class="form-group form-group-sm">
            <label class="control-label" for="Password">Password</label>
            @Html.PasswordFor(model => model.Password, new { @class = "form-control", @placeholder = "Password" })
        </div>


        <div class="buttons right">
            <input type="submit" class="btn btn-primary btn-sm" value="Login" />
        </div>
    }
</div>