-->

2 Model in 1 View in MVC 4

Introduction

In 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.



Prerequisite

I used followings:
  • .Net framework 4.0
  • Entity Framework
  • Sql Server 2008

Steps :

Just follow the steps and get result easily.

Step - 1 : Create New Project

Go 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 data

Open 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.
namespace MultiModelView
{
    using System;
    using System.Collections.Generic;
    using System.ComponentModel.DataAnnotations; 
    public partial class User
    {
        public int UserID { get; set; }
        [Required]
        public string Username { get; set; }
        [Required]
        [DataType(System.ComponentModel.DataAnnotations.DataType.Password)]
        public string Password { get; set; }
        [Required]
        public string FullName { get; set; }
    }
}

Step-4: Creare a ModelView

Here 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.

namespace OneViewTwoModel.ViewModel
{
    public class UsersLoginRegister
    {
        public User User { get; set; }
        public Login Login { get; set; }
    }

    public class Login
    {
        [Required]
        public string UserName { get; set; }
        [Required]
        [DataType( System.ComponentModel.DataAnnotations.DataType.Password)]
        public string Password { get; set; }
    }

}

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.

        public ActionResult LoginRegister(UserloginRegister lr)
        {
            return View(new UserloginRegister { Login= new Login(), User=new User() });

        }

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

@model MultiModelView.ViewModel.UserloginRegister
@{
    ViewBag.Title = "LoginRegister";}

<h2>Login Register</h2>
<div style="color:red">
    @ViewBag.Message
</div>
<table>
    <tr>
        <td><b>Login</b></td>
        <td><b>Register</b></td>
    </tr>
    <tr>
        <td>
            @using (Html.BeginForm("Login", "Home", FormMethod.Post))
            {
                <table>
                    <tr>
                        <td>Username : </td>
                        <td>@Html.TextBoxFor(a => a.Login.Username)</td>
                    </tr>
                    <tr>
                        <td>Password : </td>
                        <td>@Html.EditorFor(a => a.Login.Password)</td>
                    </tr>
                    <tr>
                        <td></td>
                        <td> <input type="submit" value="Submit" /></td>
                    </tr>
                </table>
            }
        </td>
        <td>
            @using (Html.BeginForm("Register", "Home", FormMethod.Post))
            {
                <table>
                    <tr>
                        <td>Fullname : </td>
                        <td>@Html.TextBoxFor(a => a.User.FullName)</td>
                    </tr>
                    <tr>
                        <td>Username : </td>
                        <td>@Html.TextBoxFor(a => a.User.Username)</td>
                    </tr>
                    <tr>
                        <td>Password : </td>
                        <td>@Html.EditorFor(a => a.User.Password)</td>
                    </tr>
                    <tr>
                        <td></td>
                        <td>
                            <input type="submit" value="Submit" />
                        </td>
                    </tr>
                </table>
            }
        </td>
    </tr>
</table>

@section Scripts {
    @Scripts.Render("~/bundles/jqueryval")
}

Step-7: Add Action for Login (Post Method).

Go To Controller > Add your action > write following code.

        [HttpPost]
        public ActionResult Login(UserloginRegister l)
        {
            string message = "";
            if (ModelState.IsValid)
            {
                using (MyDatabaseEntities dc = new MyDatabaseEntities())
                {
                    var v = dc.Users.Where(a => a.Username.Equals(l.Login.Username) && a.Password.Equals(l.Login.Password)).FirstOrDefault();
                    if (v != null)
                    {
                        message = "Login Success";
                        return RedirectToAction("Success", new {message=message });
                    }
                    else
                    {
                        message = "login failed";
                    }
                }
            }
            ViewBag.Message = message;
            return View("LoginRegister", l);

        }
            
        

Step-8: Add Action for Register (Post Method).

Go To Controller > Add your action > write following code.

[HttpPost]
        public ActionResult Register(UserloginRegister r)
        {
            string message = "";
            if (ModelState.IsValid)
            {
                using (MyDatabaseEntities dc = new MyDatabaseEntities())
                {
                    var v = dc.Users.Where(a => a.Username.Equals(r.User.Username)).FirstOrDefault();
                    if (v == null)
                    {
                        dc.Users.Add(r.User);
                        dc.SaveChanges();
                        message = "Successfully Registered";
                        return RedirectToAction("Success", new { message = message });
                    }
                    else
                    {
                        message = "Username no available";
                    }
                }
            }
            ViewBag.Message = message;
            return View("LoginRegister", r);

        }
        

Step-9: Add Action & view for Success Message Show.

Go To Controller > Add your action > write following code.
Action (Success)


       public ActionResult Success(string message)
        {
            ViewBag.Message = message;
            return View();
        }

View (Success)


@{
    ViewBag.Title = "Success";
}

<h2>Success</h2>
<div style="color:green">
    @ViewBag.Message

</div>

Step-10: Run Application

Look Result show in your browser.

Related Post:

Hello ! My name is Sourav Mondal. I am a software developer working in Microsoft .NET technologies since 2010.

I like to share my working experience, research and knowledge through my site.

I love developing applications in Microsoft Technologies including Asp.Net webforms, mvc, winforms, c#.net, sql server, entity framework, Ajax, Jquery, web api, web service and more.