Friday 8 December 2017

MVC Technical Interview Questions.

Multiple models in single view in MVC:

following article provides a workaround for multiple models in a single view in MVC.

Problem: suppose i have three models,MyModel,MyModel1,MyModel2 and i need to display a list of MyModel, MyModel1 and MyModel2 within a single view.
How can we do this?

Following are the model definitions for the MyModel,MyModel1 and MyModel2 classes.


MyModel.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace MultipleModelsSingleView.Models
{
public class MyModel
{
public string name { get; set; }
}
}

MyModel1.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace MultipleModelsSingleView.Models
{
public class MyModel1
{
public string country { get; set; }
}
}


MyModel2.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;


namespace MultipleModelsSingleView.Models
{
public class MyModel2
{
public List<MyModel> ListMyModel { get; set; }
public List<MyModel1> ListMyModel1 { get; set; }
public int age { get; set; }
}
}




























Following are the methods help us to get all the mymodel,mymodel1 and mymodel2.

ModelTestController.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using MultipleModelsSingleView.Models;

namespace MultipleModelsSingleView.Controllers
{
public class ModelTestController : Controller
{
// GET: ModelTest
public ActionResult Index()
{
List<MyModel> list_MyModel = new List<MyModel>();
List<MyModel1> list_MyModel1 = new List<MyModel1>();

list_MyModel.Add(new MyModel { name = "Sandeep" });
list_MyModel.Add(new MyModel { name = "Pranali" });
list_MyModel.Add(new MyModel { name = "Sandy" });

list_MyModel1.Add(new MyModel1 { country = "India" });
list_MyModel1.Add(new MyModel1 { country = "US" });
list_MyModel1.Add(new MyModel1 { country = "UK" });

MyModel2 finalView = new MyModel2();
finalView.ListMyModel = list_MyModel;
finalView.ListMyModel1 = list_MyModel1;
finalView.age = 28;

return View(finalView);
}
}
}

then write following code in the view Views---->ModelTest--->Index.cshtml

@model MultipleModelsSingleView.Models.MyModel2
@{
Layout = null;
}

<!DOCTYPE html>

<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>Index</title>
</head>
<body>
<div class="col-md-9">
@Model.age
@if(Model !=null)
{
<div class="col-md-6">
<ul>
@foreach(var name in Model.ListMyModel)
{
<li class="lsit-group-item">@name.name</li>
}
</ul>
</div>
<div class="col-md-6">
<ul>
@foreach (var country in Model.ListMyModel1)
{
<li class="lsit-group-item">@country.country</li>
}
</ul>
</div>
}
</div>
</body>
</html>


After run the application display following out put.






















No comments:

Post a Comment