IntroductionIn this post, I explain how to implement 2 model in 1 view in MVC 4. Sometimes it's required to implement a page where 2 forms exist in a single view (page) like Login & Registration in the same view. Here I have done this.
PrerequisiteI used followings:
- .Net framework 4.0
- Entity Framework
- Sql Server 2008
Steps :Just follow the steps and get result easily.
Step - 1 : Create New ProjectGo to File > New > Project > Select asp.net mvc4 web application > Entry Application Name > Click OK.
Step-2: Add a Database.Go to Solution Explorer > Right Click on App_Data folder > Add > New item > Select SQL Server Database Under Data > Enter Database name > Add.
Create a tables for save User dataOpen Database > Right Click on Table > Add New Table > Add Columns > Save > Enter table name > Ok.
In this example I have create a table Users
Step-3: Add Entity Data Model.Go to Solution Explorer > Right Click on Project name form Solution Explorer > Add > New item > Select ADO.net Entity Data Model under data > Enter model name > Add.
A popup window will come (Entity Data Model Wizard) > Select Generate from database > Next >
Chose your data connection > select your database > next > Select tables > enter Model Namespace > Finish.
After Creating Data model, we have to modify our generated entity(table) for Apply validation for required fields.
Here we need to modify User.cs file
Open file and modify as for enable validation.
Step-4: Creare a ModelViewHere in this example I need a ViewModel for get data as a single entity.
Add a Folder(ViewModel) into your project root directory. > Right Click on the folder > Add > Class > Enter Class name > Add.
Write following code to your class.
Step-5: Add Action for render 1 view both for Login & Register.Go To Controller > Add your action > write following code and Rebuild your application.
Step-6: Add View (both for Login & Register).Right Click on your Action > Add View > Enter View name > Check Create a strongly-type view > Select your model class > Select Scaffold templete > Select list > Add.
Modify Your View as follow
Step-7: Add Action for Login (Post Method).Go To Controller > Add your action > write following code.
Step-8: Add Action for Register (Post Method).Go To Controller > Add your action > write following code.
Step-9: Add Action & view for Success Message Show.Go To Controller > Add your action > write following code.
Step-10: Run ApplicationLook Result show in your browser.