How To Render Two Tables joined Data on a single View
In the previous article “Working With Single table” We have already done the from where a user will get How To Interact with Single Table. Here in this Article , we will create a Page Rendering Data by using joined Operator .
Follow the following steps in order to implement “Part 2: Working With Tables”.
Step-1 : Create Following tables in SQL ServerHere I have Created 2 tables – 1) First table that you are watching in image is EmpCat Table. 2) Second Table that you are watching in image is EmpList. 3) Third Image is the Output after Applying join operator,is the result that i want to Render on View Page.
Click To Link for Database Code- DatabaseCode.
Step-2) Use Database First Approach to Add Both Table in ASPMVC Application.
Go to Solution Explorer -> Right Click on Models Folder ->Add -> New Item ->Data ->ADO.NET Entity DataModel .
Step-3) You have to create a Custom Model class in Models Folder to Render join Data in a View.
Go to Solution Explorer -> Right Click on Models Folder ->Add -> Class ->Write the Name of class “MyViewModel”
public class MyViewModel
{
public EmpCat Cat { get; set; }
public EmpList emp { get; set; }
}
This being said I would strongly recommend you to use view models and strongly typed views instead ofViewBag
. This way you will also get Intellisense in your view which would have helped you pick the correct names.
Step-4) Now You have to create a Controller Action Method Index Controllers Folder to Render join Data in a View.
Go to Solution Explorer -> Right Click on Controllers Folder ->Add -> Controller ->Write the Name of Controller “HomeController“.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using MvcApplication51.Models;
namespace MvcApplication51.Controllers
{
public class HomeController : Controller
{
DemoEntities db = new DemoEntities();
public ActionResult Index()
{
var viewModel =
from pd in db.EmpCats
join p in db.EmpLists on pd.EmpId equals p.EmpCat
orderby p.EName
select new MyViewModel
{
Cat = pd, emp = p
};
return View(viewModel.ToList());
}
Step-5)and finally inside your strongly typed view use the view model:
@model List<MvcApplication51.Models.MyViewModel>
<table>
<tr>
<td>EmployeeName</td>
<td>EmployeeAge</td>
<td>EmployeeEmail</td>
<td>Employee Category</td> </tr>
@foreach (var item in Model)
{
<tr>
<td>@item.emp.EName</td>
<td>@item.emp.EAge</td>
<td>@item.emp.EEmail</td>
<td>@item.Cat.EmpStream</td>
</tr>
}
</table>
Amazing very Helpfull...@
ReplyDelete