Question

I've searched all over the web but not finding the solution for the following problem:

Say I have three ViewModel classes

public class ViewModelNewPerson
{
    public string PersonName;
    public string Address;
    public string EyeColor;
    //etc
}

public class ViewModelSelectPerson
{
    public int SelectedPersonId;
}

public class ViewModelComposite
{
    public ViewModelSelectPerson selectViewModel;
    public ViewModelNewPerson newPersonViewModel;
}

and I want to do the following things:

In the Controller I want to create a GET Action which uses the class ViewModelComposite as its Get model, and in the view I want the user choose from the following two available actions: to choose a existed person, and to add a new person as the selected value.

So I need to create two forms in the View, and there would be two POST Actions added to the Controller using the Post model of class ViewModelNewPerson and ViewModelSelectPerson.

My question is, how can I do the manual model binding using a Custom Model Binder that can convert the Composite class of ViewModelComposite to ViewModelNewPerson in the Action of create a new person, and to ViewModelSelectPerson in the Action of select an existing person?

EDIT:

Now I have an idea of decomposing the class ViewModelComposite and declare every property in the two classes into the composite class, and the default model binder will do the trick, I think. But that'll drop the composite pattern, and is not something I wanted.

Was it helpful?

Solution

You would use one single view model in your form, you would have a post action that receives your single view model.

In your Controller code:

public ActionResult GetSomeData(MyCustomViewModel  model){
      // add the first element
      var person = Person.Add(model.Person);
      // update the second object in model, with related / needed ID
      model.PersonContent.PersonId = person.id;
      // add in related content
      var AddedContent = PersonContent.Add(model.PersonContent);
}

single form, multiple actions, multiple tables

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top