pavanarya

Let us share the knowledge

Rendering a View from a Controller in MVC3

with 3 comments

Hi in my previous post we saw the basics of MVC3 architecture. Now let us discuss about the controller and rendering Views in depth.

View:
A view is consists of html content and it takes a model as input and render the html output using the model.
In Webforms we have an aspx page that renders the html content.

In MVC3 architecture there are two types of engines to render the views:
1. Razor view engine
2. WebForm view engine

Sample Web Form view

<%@ Page Language="C#" Inherits="System.Web.Mvc.ViewPage" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
</head>
<body>
    <div>
   Hi this is <%=firstname %>
   Please click on this url <a href="www.<%=urlname %>.wordpress.com">Click here</a>
   <% for (int i = 0; i <= 10; i++)
      { %>
  <b> <%=i%></b>
  <%} %>
    </div>
</body>
</html>

Now let us see the equivalent Razor view sample of the above web form sample.

<div>
   Hi this is @firstname
   Please click on this url <a href="www.@urlname.wordpress.com">Click here</a>
  @{
      for(int i=0;i<=10;i++)
      {
          <b>@i</b>
      }
  }
    </div>

So from the above two samples we can understand how razor view makes our life simple to some extent.

Does our application supports both the views?

The answer to this question is simply yes. We can have a mixture of razor views and webform view engines in our application.
That is some views can be written in web forms and some can be written in razor.

How requests were handled
In web form application generally a request comes to the aspx file and from there the code behind file is executed.
Similarly when we click on a button in an aspx page, the button click event handler is executed in the code-behind file.
But in mvc architecture the request first comes to controller and from there it goes to view.
So where do we have that information related to urls mapping to controller.
In Global.asax.cs we have a method called RegisterRoutes


        public static void RegisterRoutes(RouteCollection routes)
        {
            routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
          routes.MapRoute("Default", // Route name
                          "{controller}/{action}/{id}", // URL with parameters
                        new { controller = "First", action = "Index", id = UrlParameter.Optional } // Parameter defaults
                         );
        }

RouteCollection is the class that stores the information related to the url mappings.
There is a method called MapRoute that is used for mapping. It takes 3 basic parameters(ofcource it takes at max 5 parameters).
1. Routename. this is simply the unique value and defines name of the route
2.URL with parameters like {controller}/{action}/{id}
So when ever a request of this type (http://localhost:1427/First/Index/33) comes. This will execute First Controller and inside that Index function is invoked and 33 is the parameter for that index function. We can define this information inside the third parameter and by default. That means (http://localhost:1427/) will execute the controller First and the method Index.

Controller:
A controller is nothing but it has different functions which were executed initially when a request comes.

Now i am going to add a controller named as FirstController and i am going to make use of this controller in this article.

1. Right click on the controller folder and click on add and select Controller and then give it a name. Now this will add a class file that inherits from Controller class
2.By default this will have a function which returns a view

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

namespace MvcApplication2.Controllers
{
    public class FirstController : Controller
    {
        public ActionResult TestView()
        {
            return View();
        }
     }
}

Now let us build the solution and try to run the url “http://localhost:1427/First/testview&#8221;. What does this url refer to. Under the url routing section we saw that when ever we receive url of this format it is going to execute First Controller and then testview method.

Now we are going to get an error message in browser at runtime which has lot of information

So from the above message we can clearly understand few things
1. A view can be of type cshtml or vbhtml(Razor syntax)
2.A view can be of type aspx or ascx()(Webform type)
3. When ever a method inside the controller returns a view without name just like TestView() returning view using “return View();” syntax then the framework will search for the view in the following locations and it expects the name of the view to be same as controller
~/Views/First/testview.aspx
~/Views/First/testview.ascx
~/Views/Shared/testview.aspx
~/Views/Shared/testview.ascx
~/Views/First/testview.cshtml
~/Views/First/testview.vbhtml
~/Views/Shared/testview.cshtml
~/Views/Shared/testview.vbhtml

So from the third point we can understand that we are supposed to have a view with same name as of a controller and it should be either inside Shared folder inside view folder or We can create a folder with same name as controller inside View Folder and there we can add our view.

Adding a View:

We can add a view in two steps

step1
1.Browser to your controller code and place your pointer TestView and right click on it. In the popup menu we can see add view.
2. Click on add view and a window appears with view name as controller name and by default the view engine is set to razor and we can change that if we need web form engine.
3. We can discuss about other options in that window at a later point.

Now we can see a view with name TestView.cshtml in the following location View\Test folder

Now if we run http://localhost:1427/First/testview we can see the output on the browser screen.

step2

1. Create a folder with the name of the controller(First) inside the views folder. Now right click on the folder and from the popup menu click on add view. Now name it with the method name inside the controller that is going to make use of this view.
For example we are supposed to name our view as TestView as ou First controller is having a function TestView and it is going to render of TestView.cshtml.

2.We can also create a view inside the existing folder Views/Shared.

So till now we saw a controller having a method(TestView) that returns as view using “return View()” and it renders a view called TestView.cshtml.

Till now we saw about view and controller but model doesn’t come into picture.

Model:
MVC architecture without model is nothing but an application which is static.
A model is nothing but an object that represents some data. It can be something like an object to Person class that holds data like firstname,lastname,age and other information.
It can also be a dataset obtained from sql.

In this example i am having a basic model class that has two properties firstname and lastname.

MyModel.cs

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

namespace MvcApplication2.Models
{
    public class MyModel
    {
        public string firstname;
        public string lastname;
    }
}

Note:A model class can be placed inside the model folder or it can be place at different location.

How do we make use of our Model to render a view:

The answer to this question is simple
1. we can create an object of our model class inside the action method and then we can pass that object as a parameter
to View method.

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

namespace MvcApplication2.Controllers
{
    public class FirstController : Controller
    {
        public ActionResult TestView()
        {
            middlename = "pavanjj";
            Models.MyModel mod = new Models.MyModel();
            mod.firstname = "pavan";
            mod.lastname = "arya";
            return View(mod);
        }
    }
}

So in the above piece of code we are trying to create an object of our model class and then trying to assign values to our properties firstname and lastname. Then we are trying to pass that object as a parameter to our View. Now our view TestView.cshtml can make use of this object to render data.

Razor view: TestView.cshtml

@{
    //Layout = null;
}

TestView
    <div> Hai this is 
@{
    @Model.firstname;
                    @Model.lastname
    }
    </div>

Note: in the above code we will not get available properties of the model in the intelligence when we put a “.” next to @Model.
In order to get the intellisense we are supposed to add a line next to @{//Layout=null}; and above TestView. And the line is @model MvcApplication2.Models.MyModel.
This @model directive was introduced in the MVC3 which was a replacement to @inherit which specifies what model we are using.

@{
    //Layout = null;
}

@model MvcApplication2.Models.MyModel
TestView
    <div>
@{
    @Model.firstname;
                    @Model.lastname
    }
    </div>

Equivalent webform view for TestView.cshtml

TestView.aspx

<%@ Page Language="C#" Inherits="System.Web.Mvc.ViewPage" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
</head>
<body>
    <div>Hi this is
   <% var model= (Model as MvcApplication2.Models.MyModel);%>
   <%=model.firstname %>
    </div>
</body>
</html>

Note: in WebForm view we are supposed to create an object of the model inside the view and then we can make use of it.

is used to create an object of model

In my next post we can dig deep into Model view controller architecture.

Thanks,
pavan

Written by pavanarya

June 5, 2012 at 1:13 pm

Posted in MVC

3 Responses

Subscribe to comments with RSS.

  1. […] Hi, This is a continuation of my previous post that deals with model,view and render.Please read that before reading this url.. […]

  2. […] my previous posts related to MVCMVC part1,MVC part2 all my methods inside the controller are having a return type ActionResult which renders […]

  3. Neat Explanation.Good reference site for beginners.Gooooooooood Work.Thanks.

    Rathi

    August 18, 2012 at 11:17 pm


Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

Follow

Get every new post delivered to your Inbox.

Join 69 other followers

%d bloggers like this: