How to access viewModel in controller

asp.net-mvc-5 entity-framework-6

Question

I'm new to MVC. How to access two Models in the Service layer for a same function and then call it in Controller.

For example, I have a user model and Address Model.

When User tries to create the record, user will see both user information and address information in the view together.

Example: [Name, email] belongs to user model, [Address, State] belong to Address Model.

And, when the user hits submit, he will save both in different tables.

But user should see all in the same view.

How to make this possible. Hope there should be some way to do it. Because I don't want my user model to have a lot of properties.

1
0
4/4/2017 9:45:18 PM

Accepted Answer

You can create a viewmodel and unite two models.

For example :

Model ViewExample

Usuario objUsuario {get; set;}
Adreess objAdress {get; set;}

And use the ViewModel on your controller.

[Httpost]
public ActionResult Register(model ViewExample)
{
//here you can save into DB your 2 models contains ViewExample.
}

On your View, call the model like this :

@Html.TextBoxFor(m => m.objUsuario.name, new { @class = "form-control" })
@Html.TextBoxFor(m => m.objAdress.house_number, new { @class = "form-control" })
0
4/4/2017 10:55:57 PM


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow