Alexandru
Alexandru

Reputation: 12892

Posting a Partial View Model to the Same MVC Page

From the bare-bones MVC template, I have modified Manage.cshtml to include a partial, the _AccountSettingsPartial:

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

Manage.cshtml does not use @model anywhere, and it is loaded in AccountController.cs, in public ActionResult Manage(ManageMessageId? message).

_AccountSettingsPartial uses @model crapplication.Models.ManagePublicSettingsViewModel and _ChangePasswordPartial uses @model crapplication.Models.ManageUserViewModel.

Originally, AccountController.cs had just a post method for ManageUserViewModel:

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

I have tried to overload it for the other partial:

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

But this does not work, and produces the following error on a 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

How can I make my _AccountSettingsPartial page post back data from the user account management portal?

Upvotes: 1

Views: 937

Answers (1)

SethMW
SethMW

Reputation: 1082

You need to have separate forms in your partials, in order to post to different actions. (Or you could change the action of a single form with JQuery, etc., but this will be easier.)

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

...

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

You then need to uniquely name the actions.

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

...

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

Upvotes: 2

Related Questions