【问题标题】:MVC3 Partial view method not firingMVC3部分视图方法未触发
【发布时间】:2012-01-14 05:25:29
【问题描述】:

我有一个局部视图(登录,使用用户名、密码和提交按钮),并且在我的 _layout(母版页)上使用了局部视图。

所以,在我的 _layout 页面上,我有:

<div style="text-align: right">
    @Html.Partial("_LoginPartial")
</div>

我的 _LoginPartial 有以下代码:

    @if (Request.IsAuthenticated)
{
    <textarea>Welcome!
        [ @Html.ActionLink("Log Off", "Logout", "Account")]</textarea>

}
else
{
    @Html.Partial("~/Views/Account/Index.cshtml")
}

显示登录框的索引文件如下所示:

  @using GalleryPresentation.Models
@model LoginModel

<script src="../../Scripts/jquery.validate.min.js" type="text/javascript"></script>
@using (Html.BeginForm("index", "Account"))
{
    <table>
        <tr>
            <td>@Html.LabelFor(m => m.Username)</td>
            <td>@Html.TextBoxFor(m => m.Username)</td>
        </tr>
        <tr>
            <td>@Html.LabelFor(m => m.Password)</td>
            <td>@Html.PasswordFor(m => m.Password) kjkj</td>
        </tr>
        <tr>
            <td colspan="2"><input type="submit" value="Login"/></td>
        </tr>
        <tr>
            <td colspan="2">@Html.ValidationSummary()</td>
        </tr>
    </table>

}

在我的 AccountCONtroller 中,我有以下代码:

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

    [HttpPost]
    public ActionResult Index(LoginModel loginModel)
    {
        if(ModelState.IsValid)
        {
            var g = new GallaryImage();
            var user = g.LoginUser(loginModel.Username, loginModel.Password);
            if(user != null) 
            {
                FormsAuthentication.SetAuthCookie(user.username, false);
                return RedirectToAction("Index", "Home");
            }
            ModelState.AddModelError("", "Invalid Username/Password");
        }
        return View(loginModel);
    }

    public ActionResult Logout()
    {
        FormsAuthentication.SignOut();
        return RedirectToAction("Index", "Home");
    }

我在所有方法上都有断点 - 但它们永远不会被击中。按提交按钮只需将我的 URL 更改为:

http://localhost:8741/?Username=myusername&Password=mypassword

谁能发现我犯的错误?

【问题讨论】:

    标签: asp.net-mvc-3 layout partial-views


    【解决方案1】:

    由于 Html.BeginForm 默认发出 GET 请求,因此您正在从您的视图中发出 GET 请求。但是,您的操作只接受 POST 请求。

    您可以更改@using (Html.BeginForm("index", "Account"))@using (Html.BeginForm("index", "Account", FormMethod.Post))

    【讨论】:

    • 试过了,但仍然未能达到断点。我认为表单帖子默认为发布?
    • @Craig 如果表单将您重定向到http://localhost:8741/?Username=myusername&amp;Password=mypassword,则表示 HTTP GET 请求,因为浏览器将 GET 表单提交转换为查询参数。为了协助调试,您可以尝试检查浏览器发出的网络请求。您可以使用浏览器附带的开发人员工具或 Fiddler 等第三方工具来完成此操作。
    • 感谢斯蒂芬-提琴手的帮助。我发现它归结为我的 _layout 有
      标签,这正在杀死我登录框上的表单标签。固定的。谢谢。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-05-08
    • 1970-01-01
    • 1970-01-01
    • 2014-11-25
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多