Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

asp.net mvc nested view model form sumission

Is it possible to only accept post back values from a nested view model?

For example, I would like to post only the 'Address':

@Html.TextBoxFor(p => p.User.Account.Address.Street)
@Html.ValidationMessageFor(p => p.User.Account.Address.Street)

To this controller action:

[HttpPost]
public ActionResult SaveAddress(Address address) {
  // save to db here
}
Currently the values only post back if I pass the Address to it's own partial view so that the properties look like:
@Html.TextBoxFor(p => p.Street)
@Html.ValidationMessageFor(p => p.Street)

like image 421
Victor Avatar asked Aug 21 '12 15:08

Victor


1 Answers

You could specify the binding prefix:

[HttpPost]
public ActionResult SaveAddress([Bind(Prefix = "User.Account")] Address model) 
{
    ...
}

Another possibility is to use a partial:

@Html.Partial("_Address", Model.User.Account.Address)

and inside _Address.cshtml:

@model Address
@Html.TextBoxFor(p => p.Street)
@Html.ValidationMessageFor(p => p.Street)
like image 165
Darin Dimitrov Avatar answered Oct 08 '22 18:10

Darin Dimitrov