簡體   English   中英

MVC4 PartialViewResult返回視圖而不是PartialView

[英]MVC4 PartialViewResult return a view and not a PartialView

我的應用程序中有一個LogInOrRegister頁面,它調用2個子操作LogInOrRegister.cshtml

@{
    ViewBag.Title = "Log in";
}

@Html.Action("Login", "Account", new { returlUrl = ViewBag.ReturnUrl})
@Html.Action("Register", new { returlUrl = ViewBag.ReturnUrl})

@section Scripts {
    @Scripts.Render("~/bundles/jqueryval")
}

Login PartialView是:

@model Com.WTS.Portal.Models.LoginModel
<hgroup class="title">
    <h1>@ViewBag.Title</h1>
</hgroup>

<section id="loginForm">
<h2>Use a local account to log in.</h2>
@using (Html.BeginForm(new { ReturnUrl = ViewBag.ReturnUrl })) {
    @Html.AntiForgeryToken()
    @Html.ValidationSummary(true)

    <fieldset>
    <legend>Log in Form</legend>
    <ol>
        <li>
            @Html.LabelFor(m => m.Email)
            @Html.TextBoxFor(m => m.Email)
            @Html.ValidationMessageFor(m => m.Email)
        </li>
        <li>
            @Html.LabelFor(m => m.Password)
            @Html.PasswordFor(m => m.Password)
            @Html.ValidationMessageFor(m => m.Password)
        </li>
        <li>
            @Html.CheckBoxFor(m => m.RememberMe)
            @Html.LabelFor(m => m.RememberMe, new { @class = "checkbox" })
        </li>
    </ol>
    <input type="submit" value="Log in" />
    </fieldset>
}
</section>

我的AccountController.cs包含以下代碼:

    [AllowAnonymous]
    public PartialViewResult Login(string returnUrl)
    {
        ViewBag.ReturnUrl = returnUrl;
        return PartialView();
    }

    [HttpPost]
    [AllowAnonymous]
    [ValidateAntiForgeryToken]
    public PartialViewResult Login(LoginModel model, string returnUrl)
    {
        if (ModelState.IsValid && WebSecurity.Login(model.Email, model.Password, persistCookie: model.RememberMe))
        {
            RedirectToLocal(returnUrl);
        }

        // If we got this far, something failed, redisplay form
        ModelState.AddModelError("", "The user name or password provided is incorrect.");
        return PartialView(model);
    }

我正確地看到了我獲取頁面LogInOrRegister.cshtml的2個局部視圖

當我提交表單時,如果表單中存在驗證錯誤,則顯示視圖(無布局),而不是應該成為LogInOrRegster一部分的局部視圖

任何想法 ?

好的,我找到了te解決方案。 通過將路徑參數傳遞給局部視圖表單:

@using (Html.BeginForm(new { ReturnUrl = ViewBag.ReturnUrl }))

我認為我們改變了兒童行為的行為。 只有刪除路由屬性:

@using (Html.BeginForm())

PartialView在其容器中呈現。 此外,我們可以將POST操作定義為ChildActionOnly,它仍然可以工作:

[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
[ChildActionOnly]
public PartialViewResult Login(LoginModel model, string returnUrl)

因此,如果您查看https://stackoverflow.com/a/10253786/30850中的討論,您將看到使用了ChildActionOnlyAttribute,以便可以在視圖內呈現Action,但無法將其提供給瀏覽器。

如果返回類型是PartialViewResult ,請在方法public PartialViewResult Login(LoginModel model, string returnUrl)指定partialview名稱和model,否則使用ActionResult作為返回類型。 ActionResult是一個抽象類,其中PartialViewResult是一個子類。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM