European ASP.NET MVC 4 and MVC 5 Hosting

BLOG about ASP.NET MVC 3, ASP.NET MVC 4, and ASP.NET MVC 5 Hosting and Its Technology - Dedicated to European Windows Hosting Customer

ASP.NET MVC 6 Hosting - HostForLIFE.eu :: Modal Popup In MVC Application

clock February 28, 2020 11:15 by author Peter

In this post we will implement modal pop up to display the detailed information of user after clicking on detail anchor. So this is the view on which we are going to apply modal popup.

View code
Enumerable<CodeFirst.Models.FriendsInfo> 
 
@{ 
    ViewBag.Title = "Index"; 

 
<h2>Index</h2> 
 
<p> 
    @Html.ActionLink("View All", "Index") 
 
    @using (Html.BeginForm("Search", "Home", FormMethod.Post)) 
    { 
        <table> 
            <tr> 
                <td> 
                    <input type="text" id="txtName" name="searchparam" placeholder="type here to search" /> 
                </td> 
                <td> 
                    <input type="submit" id="btnSubmit" value="Search" /> 
                </td> 
            </tr> 
        </table> 
    } 
 
</p> 
<table class="table"> 
    <tr> 
        <th> 
            @Html.DisplayNameFor(model => model.Name) 
        </th> 
        <th> 
            @Html.DisplayNameFor(model => model.Mobile) 
        </th> 
        <th> 
            @Html.DisplayNameFor(model => model.Address) 
        </th> 
        <th></th> 
    </tr> 
 
    @foreach (var item in Model) 
    { 
        <tr> 
            <td> 
                @Html.DisplayFor(modelItem => item.Name) 
            </td> 
            <td> 
                @Html.DisplayFor(modelItem => item.Mobile) 
            </td> 
            <td> 
                @Html.DisplayFor(modelItem => item.Address) 
            </td> 
            <td> 
                @*@Html.ActionLink("Edit", "Edit", new { id=item.Id }) | 
                    @Html.ActionLink("Details", "Details", new { id=item.Id }) | 
                    @Html.ActionLink("Delete", "Delete", new { id=item.Id })*@ 
 
                <a href="javascript:void(0);" class="anchorDetail"  data-id="@item.Id">Details</a> 
 
            </td> 
        </tr> 
    } 
 
</table>  

As we can see we have detail anchor, with class anchorDetail and with data-id, which will get the id of clicked anchor and show the corresponding data to modal (detail view) on screen.

We have an Action method Details(int id) which will return the partial view.
public ActionResult Details(int Id) 

    FriendsInfo frnds = new FriendsInfo(); 
    frnds = db.FriendsInfo.Find(Id); 
    return PartialView("_Details",frnds); 
 

Here we added a partial view for this purpose to show detail view when user click on detail anchor in the list.

View Code
@model CodeFirst.Models.FriendsInfo 
 
<div> 
   
    <div class="modal-header"> 
        <button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button> 
        <h4 class="modal-title" id="myModalLabel">FriendsInfo</h4> 
    </div>                
                 
     
    <hr /> 
    <dl class="dl-horizontal"> 
        <dt> 
            @Html.DisplayNameFor(model => model.Name) 
        </dt> 
 
        <dd> 
            @Html.DisplayFor(model => model.Name) 
        </dd> 
 
        <dt> 
            @Html.DisplayNameFor(model => model.Mobile) 
        </dt> 
 
        <dd> 
            @Html.DisplayFor(model => model.Mobile) 
        </dd> 
 
        <dt> 
            @Html.DisplayNameFor(model => model.Address) 
        </dt> 
 
        <dd> 
            @Html.DisplayFor(model => model.Address) 
        </dd> 
 
    </dl> 
</div> 


We have a div for modal pop-up.

<div id='myModal' class='modal'> 
    <div class="modal-dialog"> 
        <div class="modal-content"> 
            <div id='myModalContent'></div> 
        </div> 
    </div>  
     
</div>  


Here is the script for showing modal (partial view) on above div when user click on detail anchor. Here we used Ajax call for this purpose.

Script
@section scripts 

    <script src="~/Scripts/jquery-1.10.2.min.js"></script> 
    <script src="~/Scripts/bootstrap.js"></script> 
    <script src="~/Scripts/bootstrap.min.js"></script> 
<script> 
    var TeamDetailPostBackURL = '/Home/Details'; 
    $(function () { 
        $(".anchorDetail").click(function () { 
            debugger; 
            var $buttonClicked = $(this); 
            var id = $buttonClicked.attr('data-id'); 
            var options = { "backdrop": "static", keyboard: true }; 
            $.ajax({ 
                type: "GET", 
                url: TeamDetailPostBackURL, 
                contentType: "application/json; charset=utf-8", 
                data: { "Id": id }, 
                datatype: "json", 
                success: function (data) { 
                    debugger; 
                    $('#myModalContent').html(data); 
                    $('#myModal').modal(options); 
                    $('#myModal').modal('show');                   
 
                }, 
                error: function () { 
                    alert("Dynamic content load failed."); 
                } 
            }); 
        }); 
        //$("#closebtn").on('click',function(){ 
        //    $('#myModal').modal('hide');   
 
        $("#closbtn").click(function () { 
            $('#myModal').modal('hide'); 
        });       
    }); 
    
</script> 
 

HostForLIFE.eu ASP.NET MVC 6 Hosting
HostForLIFE.eu is European Windows Hosting Provider which focuses on Windows Platform only. We deliver on-demand hosting solutions including Shared hosting, Reseller Hosting, Cloud Hosting, Dedicated Servers, and IT as a Service for companies of all sizes. We have customers from around the globe, spread across every continent. We serve the hosting needs of the business and professional, government and nonprofit, entertainment and personal use market segments.



European ASP.NET Core Hosting - HostForLIFE.eu :: Multiple Models in Single View in MVC

clock February 7, 2020 10:31 by author Peter

In MVC we cannot pass multiple models from a controller to the single view. This article provides a workaround for multiple models in a single view in MVC.

Problem Statement

Suppose I have two models, Teacher and Student, and I need to display a list of teachers and students within a single view. How can we do this?

The following are the model definitions for the Teacher and Student classes.

public class Teacher  
{  
    public int TeacherId { get; set; }  
    public string Code { get; set; }  
    public string Name { get; set; }  
}   
  
public class Student  
{  
    public int StudentId { get; set; }  
    public string Code { get; set; }  
    public string Name { get; set; }  
    public string EnrollmentNo { get; set; }  
}  

The following are the methods that help us to get all the teachers and students.

private List<Teacher> GetTeachers()  
{  
    List<Teacher> teachers = new List<Teacher>();  
    teachers.Add(new Teacher { TeacherId = 1, Code = "TT", Name = "Peter" });  
    teachers.Add(new Teacher { TeacherId = 2, Code = "JT", Name = "Scott" });  
    teachers.Add(new Teacher { TeacherId = 3, Code = "RT", Name = "Paul" });  
    return teachers;  
}   
  
public List<Student> GetStudents()  
{  
    List<Student> students = new List<Student>();  
    students.Add(new Student { StudentId = 1, Code = "L0001", Name = "Thomas", EnrollmentNo = "201404150001" });  
    students.Add(new Student { StudentId = 2, Code = "L0002", Name = "Brian", EnrollmentNo = "201404150002" });  
    students.Add(new Student { StudentId = 3, Code = "L0003", Name = "Chester", EnrollmentNo = "201404150003" });  
    return students;  
}  

There are many ways to use multiple models with a single view. Here I will explain ways one by one.

1. Using Dynamic Model

ExpandoObject (the System.Dynamic namespace) is a class that was added to the .Net Framework 4.0 that allows us to dynamically add and remove properties onto an object at runtime. Using this ExpandoObject, we can create a new object and can add our list of teachers and students into it as a property. We can pass this dynamically created object to the view and render list of the teacher and student.

Controller Code

public class HomeController : Controller  
{  
    public ActionResult Index()  
    {  
        ViewBag.Message = "Welcome to my demo!";  
        dynamic mymodel = new ExpandoObject();  
        mymodel.Teachers = GetTeachers();  
        mymodel.Students = GetStudents();  
        return View(mymodel);  
    }  
}  

We can define our model as dynamic (not a strongly typed model) using the @model dynamic keyword.

View Code

@using MultipleModelInOneView;  
@model dynamic  
@{  
    ViewBag.Title = "Home Page";  
}  
<h2>@ViewBag.Message</h2>  
   
<p><b>Teacher List</b></p>  
   
<table>  
    <tr>  
        <th>Id</th>  
        <th>Code</th>  
        <th>Name</th>  
    </tr>  
    @foreach (Teacher teacher in Model.Teachers)  
    {  
        <tr>  
            <td>@teacher.TeacherId</td>  
            <td>@teacher.Code</td>  
            <td>@teacher.Name</td>  
        </tr>  
    }  
</table>  
   
<p><b>Student List</b></p>  
   
<table>  
    <tr>  
        <th>Id</th>  
        <th>Code</th>  
        <th>Name</th>  
        <th>Enrollment No</th>  
    </tr>  
    @foreach (Student student in Model.Students)  
    {  
        <tr>  
            <td>@student.StudentId</td>  
            <td>@student.Code</td>  
            <td>@student.Name</td>  
            <td>@student.EnrollmentNo</td>  
        </tr>  
    }  
</table>  

2. Using View Model

ViewModel is nothing but a single class that may have multiple models. It contains multiple models as a property. It should not contain any method. In the above example, we have the required View model with two properties. This ViewModel is passed to the view as a model. To get intellisense in the view, we need to define a strongly typed view.

public class ViewModel  
{  
    public IEnumerable<Teacher> Teachers { get; set; }  
    public IEnumerable<Student> Students { get; set; }  
}  

Controller code

public ActionResult IndexViewModel()  
{  
    ViewBag.Message = "Welcome to my demo!";  
    ViewModel mymodel = new ViewModel();  
    mymodel.Teachers = GetTeachers();  
    mymodel.Students = GetStudents();  
    return View(mymodel);  
}  

View code

@using MultipleModelInOneView;  
@model ViewModel   
@{  
    ViewBag.Title = "Home Page";  
}  
<h2>@ViewBag.Message</h2>  
   
<p><b>Teacher List</b></p>  
   
<table>  
    <tr>  
        <th>Id</th>  
        <th>Code</th>  
        <th>Name</th>  
    </tr>  
    @foreach (Teacher teacher in Model.Teachers)  
    {  
        <tr>  
            <td>@teacher.TeacherId</td>  
            <td>@teacher.Code</td>  
            <td>@teacher.Name</td>  
        </tr>  
    }  
</table>  
   
<p><b>Student List</b></p>  
   
<table>  
    <tr>  
        <th>Id</th>  
        <th>Code</th>  
        <th>Name</th>  
        <th>Enrollment No</th>  
    </tr>  
    @foreach (Student student in Model.Students)  
    {  
        <tr>  
            <td>@student.StudentId</td>  
            <td>@student.Code</td>  
            <td>@student.Name</td>  
            <td>@student.EnrollmentNo</td>  
        </tr>  
    }  
</table>  

3. Using ViewData
ViewData is used to transfer data from the controller to the view. ViewData is a dictionary object that may be accessible using a string as the key. Using ViewData, we can pass any object from the controller to the view. The Type Conversion code is required when enumerating in the view.
For the preceding example, we need to create ViewData to pass a list of teachers and students from the controller to the view.

Controller Code
public
 ActionResult IndexViewData()  

{  
    ViewBag.Message = "Welcome to my demo!";  
    ViewData["Teachers"] = GetTeachers();  
    ViewData["Students"] = GetStudents();  
    return View();  
}  

View Code

@using MultipleModelInOneView;  
@{  
    ViewBag.Title = "Home Page";  
}  
<h2>@ViewBag.Message</h2>  
 <p><b>Teacher List</b></p>   
@{  
  
   IEnumerable<Teacher> teachers = ViewData["Teachers"] as IEnumerable<Teacher>;  
   IEnumerable<Student> students = ViewData["Students"] as IEnumerable<Student>;  
}  
<table>  
    <tr>  
        <th>Id</th>  
        <th>Code</th>  
        <th>Name</th>  
    </tr>  
    @foreach (Teacher teacher in teachers)  
    {  
        <tr>  
            <td>@teacher.TeacherId</td>  
            <td>@teacher.Code</td>  
            <td>@teacher.Name</td>  
        </tr>  
    }  
</table>  
 <p><b>Student List</b></p>  
<table>  
    <tr>  
        <th>Id</th>  
        <th>Code</th>  
        <th>Name</th>  
        <th>Enrollment No</th>  
    </tr>  
    @foreach (Student student in students)  
    {  
        <tr>  
            <td>@student.StudentId</td>  
            <td>@student.Code</td>  
            <td>@student.Name</td>  
            <td>@student.EnrollmentNo</td>  
        </tr>  
    }  
</table>  

4. Using ViewBag
ViewBag is similar to ViewData and is also used to transfer data from the controller to the view. ViewBag is a dynamic property. ViewBag is just a wrapper around the ViewData.

Controller Code

public ActionResult IndexViewBag()  
{  
    ViewBag.Message = "Welcome to my demo!";  
    ViewBag.Teachers = GetTeachers();  
    ViewBag.Students = GetStudents();  
    return View();  
}  

View Code

@using MultipleModelInOneView;  
@{  
    ViewBag.Title = "Home Page";  
}  
<h2>@ViewBag.Message</h2>  
   
<p><b>Teacher List</b></p>  
   
<table>  
    <tr>  
        <th>Id</th>  
        <th>Code</th>  
        <th>Name</th>  
    </tr>  
    @foreach (Teacher teacher in ViewBag.Teachers)  
    {  
        <tr>  
            <td>@teacher.TeacherId</td>  
            <td>@teacher.Code</td>  
            <td>@teacher.Name</td>  
        </tr>  
    }  
</table>  
   
<p><b>Student List</b></p>  
   
<table>  
    <tr>  
        <th>Id</th>  
        <th>Code</th>  
        <th>Name</th>  
        <th>Enrollment No</th>  
    </tr>  
    @foreach (Student student in ViewBag.Students)  
    {  
        <tr>  
            <td>@student.StudentId</td>  
            <td>@student.Code</td>  
            <td>@student.Name</td>  
            <td>@student.EnrollmentNo</td>  
        </tr>  
    }  
</table> 

5. Using Tuple

A Tuple object is an immutable, fixed-size and ordered sequence object. It is a data structure that has a specific number and sequence of elements. The .NET framework supports tuples up to seven elements. Using this tuple object we can pass multiple models from the controller to the view.

Controller Code

public ActionResult IndexTuple() 
{  
    ViewBag.Message = "Welcome to my demo!";  
    var tupleModel = new Tuple<List<Teacher>, List<Student>>(GetTeachers(), GetStudents());  
    return View(tupleModel);  
}  

View Code

@using MultipleModelInOneView;  
@model Tuple <List<Teacher>, List <Student>>  
@{  
    ViewBag.Title = "Home Page";  
}  
<h2>@ViewBag.Message</h2>   
<p><b>Teacher List</b></p>  
<table>  
    <tr>  
        <th>Id</th>  
        <th>Code</th>  
        <th>Name</th>  
    </tr>  
    @foreach (Teacher teacher in Model.Item1)  
    {  
        <tr>  
            <td>@teacher.TeacherId</td>  
            <td>@teacher.Code</td>  
            <td>@teacher.Name</td>  
        </tr>  
    }  
</table>  
<p><b>Student List</b></p>  
<table>  
    <tr>  
        <th>Id</th>  
        <th>Code</th>  
        <th>Name</th>  
        <th>Enrollment No</th>  
    </tr>  
    @foreach (Student student in Model.Item2)  
    {  
        <tr>  
            <td>@student.StudentId</td>  
            <td>@student.Code</td>  
            <td>@student.Name</td>  
            <td>@student.EnrollmentNo</td>  
        </tr>  
    }  
</table>  

6. Using Render Action Method
A Partial View defines or renders a partial view within a view. We can render some part of a view by calling a controller action method using the Html.RenderAction method. The RenderAction method is very useful when we want to display data in the partial view. The disadvantages of this method is that there are only multiple calls of the controller.


In the following example, I have created a view (named partialView.cshtml) and within this view I called the html.RenderAction method to render the teacher and student list.

Controller Code

public ActionResult PartialView()  
{  
    ViewBag.Message = "Welcome to my demo!";  
    return View();  
}  
   
/// <summary>  
/// Render Teacher List  
/// </summary>  
/// <returns></returns>  
public PartialViewResult RenderTeacher()  
{  
    return PartialView(GetTeachers());  
}  
   
/// <summary>  
/// Render Student List  
/// </summary>  
/// <returns></returns>  
public PartialViewResult RenderStudent()  
{  
    return PartialView(GetStudents());  
 

View Code

@{ 
   ViewBag.Title = "PartialView";  
<h2>@ViewBag.Message</h2>  
<div>  
    @{  
        Html.RenderAction("RenderTeacher");  
        Html.RenderAction("RenderStudent");  
    }  
</div>  

RenderTeacher.cshtml

@using MultipleModelInOneView;  
@model IEnumerable<MultipleModelInOneView.Teacher>  
 <p><b>Teacher List</b></p>  
<table>  
    <tr>  
        <th>Id</th>  
        <th>Code</th>  
        <th>Name</th>  
    </tr>  
    @foreach (Teacher teacher in Model)  
    {  
        <tr>  
            <td>@teacher.TeacherId</td>  
            <td>@teacher.Code</td>  
            <td>@teacher.Name</td>  
        </tr>  
    }  
  1. </table>  

RenderStudent.cshtml

@using MultipleModelInOneView;  
@model IEnumerable<MultipleModelInOneView.Student>   
  
<p><b>Student List</b></p>  
<table>  
    <tr>  
        <th>Id</th>  
        <th>Code</th>  
        <th>Name</th>  
        <th>Enrollment No</th>  
    </tr>  
    @foreach (Student student in Model)  
    {  
        <tr>  
            <td>@student.StudentId</td>  
            <td>@student.Code</td>  
            <td>@student.Name</td>  
            <td>@student.EnrollmentNo</td>  
        </tr>  
    }  
</table> 

Conclusion

This article helps us to learn how to pass multiple models from the controller to the view. I hope this will be helpful for beginners.



About HostForLIFE.eu

HostForLIFE.eu is European Windows Hosting Provider which focuses on Windows Platform only. We deliver on-demand hosting solutions including Shared hosting, Reseller Hosting, Cloud Hosting, Dedicated Servers, and IT as a Service for companies of all sizes.

We have offered the latest Windows 2016 Hosting, ASP.NET Core 2.2.1 Hosting, ASP.NET MVC 6 Hosting and SQL 2017 Hosting.


Tag cloud

Sign in