Saturday, 10 December 2016

Difference between HttpPost and HttpPut

The fundamental difference between the POST and PUT requests is reflected in the different meaning of the Request-URI. The URI in a POST request identifies the resource that will handle the enclosed entity. That resource might be a data-accepting process, a gateway to some other protocol, or a separate entity that accepts annotations. In contrast, the URI in a PUT request identifies the entity enclosed with the request – the user agent knows what URI is intended and the server MUST NOT attempt to apply the request to some other resource.
It doesn’t mention anything about the difference between updating/creating, because that’s not what it’s about. It’s about the difference between this:
obj.set_attribute(value) # A POST request.
And this:
obj.attribute = value # A PUT request.

Tuesday, 30 August 2016

Correct version of C# and .NET framework

What will be the Version of C# if you are using .NET Version 3.5??

First it's sad to see these kind of questions in senior interviews as they do not test developers capability.
There is no direct mapping of language and framework versions. In other words if you have .NET 3.5 does not mean that you have C# 3.5. For .NET 3.5 we its C# 3.0. Mostly languages do not have minor versions. In other words you will not see C# 3.5 , C# 4.5 and so on. It mostly major versions. Below is the list of framework and C# versions.

C# 1.0.NET 1.0
C# 1.2.NET 1.1
C# 2.0.NET 2.0
C# 3.0.NET 3.5
C# 4.0.NET 4
C# 5.0.NET 4.5
C# 6.0.NET 4.6

Thursday, 18 August 2016

Why are there two web.config files in my MVC application a) 1 in the root directory b) 1 in the views directory

The settings should go into the web.config at the application root. The web.config in the views folder is there to block direct access to the view aspx pages which should only get served through controllers.

OR,

The web.config in the Views directory just has one significant entry, which blocks direct access:
<add path="*" verb="*"
      type="System.Web.HttpNotFoundHandler"/>
This is so someone cannot manually try to go to http://www.yoursite.com/views/main/index.aspxand load the page outside the MVC pipeline.

OR,
/Views/Web.config
This is not your application’s main web.config file. It just contains a directive instructing the web server not to serve any *.aspx files under /Views (because they should be rendered by a controller, not invoked directly like classic WebForms *.aspx files). This file also contains configuration needed to make the standard ASP.NET ASPX page compiler work properly with ASP.NET MVC view template syntax.
/Web.config
This defines your application configuration.
This is from the book Pro ASP.NET MVC Framework

Friday, 12 August 2016

How many ways to bind a single view in multiple models?

How many ways to bind a single view in multiple models?

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 { getset; }
    public string Code { getset; }
    public string Name { getset; }
public class Student{
    public int StudentId { getset; }
    public string Code { getset; }
    public string Name { getset; }
    public string EnrollmentNo { getset; }
}
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 = "Tejas Trivedi" });
    teachers.Add(new Teacher { TeacherId = 2, Code = "JT", Name = "Jignesh Trivedi" });
    teachers.Add(new Teacher { TeacherId = 3, Code = "RT", Name = "Rakesh Trivedi" });
    return teachers;
public List<Student> GetStudents(){
    List<Student> students = new List<Student>();
    students.Add(new Student { StudentId = 1, Code = "L0001", Name = "Amit Gupta", EnrollmentNo ="201404150001" });
    students.Add(new Student { StudentId = 2, Code = "L0002", Name = "Chetan Gujjar", EnrollmentNo ="201404150002" });
    students.Add(new Student { StudentId = 3, Code = "L0003", Name = "Bhavin Patel", EnrollmentNo ="201404150003" });
    return students;
}
Required output


Solution
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 { getset; }
    public IEnumerable<Student> Students { getset; }
}
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>    }
</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.