5

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)

1 Answer 1

7

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)
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks, the Bind Prefix is exactly what I was looking for.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.