
There is a common scenario, which is being asked quite a lot in ASP.NET MVC platforms. Thus, I have decided to demonstrate my take on this particular scenario. The scenario is as follows; i.e., create a single page, which will display the data from two different view models. Now, the question that arises here is if the ASP.NET MVC platform only attaches a single model to a single view, how can this be achieved? Let me demonstrate how this is done.
Today, I shall be demonstrating about how to utilize multiple view models into a single view in an ASP.NET MVC5 platform.
Following are some prerequisites before you proceed further in this tutorial:
- Knowledge of ASP.NET MVC5.
- Knowledge of HTML.
- Knowledge of JavaScript.
- Knowledge of Bootstrap.
- Knowledge of jQuery.
- Knowledge of C# programming.
You can download the complete source code for this tutorial or you can follow the step by step discussion below. The sample code is being developed in Microsoft Visual Studio 2015 Enterprise.
Before we jump into the technical working of this scenario, let's build a little conceptual understanding of how will we achieve this scenario in an ASP.NET MVC5 platform. To do achieve this, we will proceed in our code, as shown below i.e.
Step 1
We have two independent models Register Model & ResultSet Model
Step 2
Since we know the constraint on ASP.NET MVC platform i.e. we can only attach a single model to a single view. So, here we will create a parent place holder kind of model; i.e., Common Model, and make our actual view models the child to this model, as shown below
Step 3
After combining our two separate models into a single model, we then can easily attach our common place holder model to our single view, as shown below.
Now, let's see, how can we code this.
- Create a new MVC Web project and name it MultiModelSingleView.
- Create a file LoginObj.cs under Models folder and replace the code given below in it
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Web;
- namespace MultiModelSingleView.Models
- {
- public class LoginObj
- {
- public int Id { get; set; }
- public string Username { get; set; }
- public string Password { get; set; }
- }
- }
Now, create our view models files -- AccountViewModel.cs, ResultSetViewModel.cs & CommonViewModel.cs -- under Models folder and replace the code given below in each file accordingly, as shown below
Replace the code given below in AccountViewModel.cs file
- using System.Collections.Generic;
- using System.ComponentModel.DataAnnotations;
- namespace MultiModelSingleView.Models
- {
- public class AccountViewModel
- {
- [Display(Name = "Id")]
- public int Id { get; set; }
- [Display(Name = "Enter Username")]
- public string Username { get; set; }
- [Display(Name = "Enter Password")]
- public string Password { get; set; }
- }
- }
Replace the code given below in ResultSetViewModel.cs file i.e.
- using System.Collections.Generic;
- using System.ComponentModel.DataAnnotations;
- namespace MultiModelSingleView.Models
- {
- public class ResultSetViewModel
- {
- [Display(Name = "Result")]
- public List<LoginObj> ResultSet { get; set; }
- }
- }
Replace the code given below in CommonViewModel.cs file i.e.
- using System.Collections.Generic;
- using System.ComponentModel.DataAnnotations;
- namespace MultiModelSingleView.Models
- {
- public class CommonViewModel
- {
- public AccountViewModel AccountVM { get; set; }
- public ResultSetViewModel ResultSetVM { get; set; }
- }
- }
In all the snippets given above, we have created our view models according to the conceptual understanding, which we have developed.
Create a new controller file AccountController.cs under Controllers folder and replace the code given below in it
- //-----------------------------------------------------------------------
- // <copyright file="HomeController.cs" company="None">
- // Copyright (c) Allow to distribute this code.
- // </copyright>
- // <author>Asma Khalid</author>
- //-----------------------------------------------------------------------
- namespace MultiModelSingleView.Controllers
- {
- using System;
- using System.Globalization;
- using System.Linq;
- using System.Security.Claims;
- using System.Threading.Tasks;
- using System.Web;
- using System.Web.Mvc;
- using Microsoft.AspNet.Identity;
- using Microsoft.AspNet.Identity.Owin;
- using Microsoft.Owin.Security;
- using MultiModelSingleView.Models;
- using System.Collections.Generic;
- using System.IO;
- using System.Reflection;
- public class AccountController : Controller
- {
- #region Register method
- #region GET: /Account/Register
- //
- // GET: /Account/Register
- [AllowAnonymous]
- public ActionResult Register()
- {
- // Initialization.
- CommonViewModel model = new CommonViewModel();
- model.AccountVM = new AccountViewModel();
- model.ResultSetVM = new ResultSetViewModel();
- // Get Result
- model.ResultSetVM.ResultSet = this.LoadData();
- return View(model);
- }
- #endregion
- #region POST: /Account/Register
- //
- // POST: /Account/Register
- [HttpPost]
- [AllowAnonymous]
- [ValidateAntiForgeryToken]
- public ActionResult Register(CommonViewModel model)
- {
- if (ModelState.IsValid)
- {
- // Inserting.
- this.StoreData(model.AccountVM.Username, model.AccountVM.Password);
- // Get Result
- model.ResultSetVM = new ResultSetViewModel();
- model.ResultSetVM.ResultSet = this.LoadData();
- }
- // If we got this far, something failed, redisplay form
- return View(model);
- }
- #endregion
- #endregion
- #region Helpers
- #region Load Data
- /// <summary>
- /// Load data method.
- /// </summary>
- /// <returns>Returns - Data</returns>
- private List<LoginObj> LoadData()
- {
- // Initialization.
- List<LoginObj> lst = new List<LoginObj>();
- try
- {
- // Initialization.
- string line = string.Empty;
- string srcFilePath = "content/files/login_list.txt";
- var rootPath = Path.GetDirectoryName(Assembly.GetExecutingAssembly().CodeBase);
- var fullPath = Path.Combine(rootPath, srcFilePath);
- string filePath = new Uri(fullPath).LocalPath;
- StreamReader sr = new StreamReader(new FileStream(filePath, FileMode.Open, FileAccess.Read));
- // Read file.
- while ((line = sr.ReadLine()) != null)
- {
- // Initialization.
- LoginObj infoObj = new LoginObj();
- string[] info = line.Split(',');
- // Setting.
- infoObj.Id = Convert.ToInt32(info[0].ToString());
- infoObj.Username = info[1].ToString();
- infoObj.Password = info[2].ToString();
- // Adding.
- lst.Add(infoObj);
- }
- // Closing.
- sr.Dispose();
- sr.Close();
- }
- catch (Exception ex)
- {
- // info.
- Console.Write(ex);
- }
- // info.
- return lst;
- }
- #endregion
- #region Store Data
- /// <summary>
- /// Store data method.
- /// </summary>
- private void StoreData(string username, string password)
- {
- // Initialization.
- LoginObj obj = new LoginObj();
- try
- {
- // Setting.
- int idVal = this.LoadData().Select(p => p).ToList().Count > 0
- ? (this.LoadData().OrderByDescending(p => p.Id).Select(p => p.Id).FirstOrDefault()) + 1
- : 1;
- // Initialization.
- string line = string.Empty;
- string srcFilePath = "content/files/login_list.txt";
- var rootPath = Path.GetDirectoryName(Assembly.GetExecutingAssembly().CodeBase);
- var fullPath = Path.Combine(rootPath, srcFilePath);
- string filePath = new Uri(fullPath).LocalPath;
- StreamWriter sw = new StreamWriter(new FileStream(filePath, FileMode.Append, FileAccess.Write));
- // Write file.
- string content = idVal.ToString() + "," + username + "," + password;
- sw.WriteLine(content);
- // Closing.
- sw.Dispose();
- sw.Close();
- }
- catch (Exception ex)
- {
- // info.
- Console.Write(ex);
- }
- }
- #endregion
- #endregion
- }
- }



Anmol ButtPosted Dec 5, 2018, 8:41 AM
I am having errors in html page like (name 'model' etc doesn't exit in current context) what should i do?
yusuf ogundijiPosted Jul 4, 2018, 10:46 AM
What if i want to use paging in the index method how do i do that
Dilshad AliPosted Apr 13, 2017, 2:47 AM
Nice article Asma. Alternate method is also used through Expando object.
Asma KhalidPosted Apr 13, 2017, 2:03 AM
Thank you all for your support.
Manav PandyaPosted Apr 13, 2017, 12:25 AM
I have vs 2013 installed how can i convert or run in vs 2013 ??
Manav PandyaPosted Apr 13, 2017, 12:11 AM
Thanks for sharing ma'm .....
Hamid KhanPosted Apr 12, 2017, 11:38 PM
Nice article For start-up engineers