将一个局部视图模型发布到同一个MVC页面

本文关键字:同一个 页面 MVC 模型 视图 局部 一个 | 更新日期: 2023-09-27 18:17:10

从骨架MVC模板中,我修改了Manage.cshtml以包含部分_AccountSettingsPartial:

<section id="accountSettings">            
    @Html.Partial("_AccountSettingsPartial")
</section>
@if (ViewBag.HasLocalPassword)
{
    @Html.Partial("_ChangePasswordPartial")
}

Manage.cshtml没有在任何地方使用@model,并且在AccountController.cs中加载,在public ActionResult Manage(ManageMessageId? message)中加载。

_AccountSettingsPartial使用@model crapplication.Models.ManagePublicSettingsViewModel, _ChangePasswordPartial使用@model crapplication.Models.ManageUserViewModel

最初,AccountController.cs只有ManageUserViewModel的post方法:

[HttpPost]
[ValidateAntiForgeryToken]
public async Task<ActionResult> Manage(ManageUserViewModel model)

我已经尝试为另一个部分重载它:

[HttpPost]
[ValidateAntiForgeryToken]
public async Task<ActionResult> Manage(ManagePublicSettingsViewModel model)

但是这不起作用,并且在post上产生以下错误:

System.Reflection.AmbiguousMatchException: The current request for action 'Manage' on controller type 'AccountController' is ambiguous between the following action methods:
System.Threading.Tasks.Task`1[System.Web.Mvc.ActionResult] Manage(crapplication.Models.ManagePublicSettingsViewModel) on type crapplication.Controllers.AccountController
System.Threading.Tasks.Task`1[System.Web.Mvc.ActionResult] Manage(crapplication.Models.ManageUserViewModel) on type crapplication.Controllers.AccountController

如何使我的_AccountSettingsPartial页面从用户帐户管理门户发布回数据?

将一个局部视图模型发布到同一个MVC页面

您需要在您的部分中有单独的表单,以便发布到不同的操作。(或者您可以使用JQuery更改单个表单的动作,等等,但这将更容易。)

@using (Html.BeginForm("ManagePublicSettings", "Account", FormMethod.Post))
...
@using (Html.BeginForm("ManageUser", "Account", FormMethod.Post))

然后需要唯一地命名操作。

[HttpPost]
[ValidateAntiForgeryToken]
public async Task<ActionResult> ManagePublicSettings(ManagePublicSettingsViewModel model)
...
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<ActionResult> ManageUser(ManageUserViewModel model)