Thursday, July 27, 2017

ASP.Net MVC - Multiple Models in Single View - Part2

In last post, we have talked about different approaches to pass the multiple models in single view. We have also looked some of them like Dynamic,View Data and View Bag.

This post is the continuation of previous post. Here we will see the use of ViewModel,Tuple and ViewComponent for passing multiple model in single view . Let's first see what was our problem statement-

Problem Statement

We have two models Student and Course and we need to show the the list of Students and Courses in a single view.

Below are the model definition for Student and Course
public class Student
    public int StudentID { get; set; }
    public string StudentName { get; set; }       

public class Course
    public int CourseID { get; set; }
    public string CourseName { get; set; }

Solutions to achieve

Here we will see ViewModel,Tuple and ViewComponent to achieve our requirement

1. View Model

ViewModel is a class which contains the properties which are represented in view or represents the data that we want to display on our view.

If we want to create a View where we want to display list of Students and Courses then we will create our View Model (StudentCourseViewModel.cs).

Friday, July 7, 2017

ASP.Net MVC - Custom Model Binding

In last article, we have discussed about what is ASP.NET Model binding and saw a basic introduction to the Model Binder. In this post we will see creating Custom Model Binding in ASP.Net MVC with simple example.

Model Binder in ASP.NET MVC

For model binding MVC uses the following types-

IModelBinder interface - This defines methods that are required for a Model Binder, like the BindModelAsync method. This method is responsible for binding a model to some values using ModelBindingContext

IModelBinderProvider interface - This interface contains methods that enables dynamic implementation of model binding for classes which implement the IModelBinder interface. This is used to manage the custom binder for the type of data posted by the end-user in views.

Creating Custom Model Binder

We creating our custom model binder by implementing the IModelBinder and IModelBinderProvider interfaces. Let see how we will do that.

Note :I have used ASP.Net MVC Core project here.All the codes are in ASP.Net MVC Core.

If You Enjoyed This Post Please Take 5 Seconds To Share It.

^ Scroll to Top hgpromo