简体   繁体   中英

How do you bind a viewmodel subclass values in an action?

I have Two ViewModels

CreateEventViewModel
CreateAccountViewModel

CreateEventViewModel looks like this

public class CreateEventViewModel
{
    [Required]
    [Display(Name = "Name")]
    public string Name { get; set; }

    public CreateAccountViewModel CreateAccountViewModel;
}

And in the view I can use

@Html.EditorFor(model => model.name)
@Html.EditorFor(model => model.CreateAccountViewModel.Email)

All is great so far, but how am I to bind the value to CreateAccountViewModel.Email ?

The binding to CreateEventViewModel.Name works great with this setup

public ActionResult Create([Bind(Include = "Name")] CreateEventViewModel eventViewModel){
    ...
}

But how would i write to get the binding towards CreateEventViewModel.CreateAccountViewModel.Email ?

I guess you should mention get set

public virtual CreateAccountViewModel CreateAccountView {get; set;}

now Email property in CreateAccountViewModel should be accessible inside your create method

public ActionResult Create(CreateEventViewModel eventViewModel){
    var email = eventViewModel.CreateAccountView.Email;
}

When we pass Model object as a parameter ASP.net MVC automatically does model binding for you, ASP.NET MVC Model all the data coming from HTTP world and use the DefaultModelBinder class which magically does all the type conversion and mapping of all these values to the Model properties.

In the Create action we are already using model binding. But to make binding work your html input tags attribute id and name should be same as model properties. ex: <input class="textbox" id="Name" name="Name" type"text"> and for CreateAccountViewModel inside CreateEventViewModel do use ModelObject.PropertyName as in input tag below

<input class="textbox" id="CreateAccountView.Email" name="CreateAccountView.Email" type"text">

Here is how to bind the Email field of a member class (CreateAccountViewModel) to an action. You just need to pass the member class to the action;

public ActionResult Create(
[Bind(Include = "Name")] 
     CreateEventViewModel eventViewModel,
[Bind(Include = "Email")] 
     CreateAccountViewModel accountViewModel){
    ...
}

as an aside, this also works although you can't exclude other properties of the member class such as say, Email2. By the way, in this example I have renamed the field name to accountViewModel since using CreateAccountViewModel creates ambiguities

public ActionResult Create(
[Bind(Include = "Name,accountViewModel")] 
     CreateEventViewModel eventViewModel){
    ...
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM