mvc asp.net q & a series

22
MVC ASP.NET Q & A series 1. How to create a simple "Hello World" using ASP.NET MVC template? - Lab 1 Lab1:- Creating a simple hello world ASP.NET MVC Application In this lab we will create a simple hello world program using MVC template. So we will create a simple controller, attach the controller to simple index.aspx page and view the display on the browser. Step1:- Create project Create a new project by selecting the MVC 2 empty web application template as shown in the below figure. Once you click ok, you have a readymade structure with appropriate folders where you can add controllers, models and views.

Upload: abhi

Post on 22-Apr-2015

39 views

Category:

Documents


5 download

TRANSCRIPT

Page 1: Mvc ASP.net q & a Series

MVC ASP.NET Q & A series

1. How to create a simple "Hello World" using ASP.NET MVC template? - Lab 1

Lab1:- Creating a simple hello world ASP.NET MVC ApplicationIn this lab we will create a simple hello world program using MVC template. So we will create a simple controller, attach the controller to simple index.aspx page and view the display on the browser.Step1:- Create projectCreate a new project by selecting the MVC 2 empty web application template as shown in the below figure.

Once you click ok, you have a readymade structure with appropriate folders where you can add controllers, models and views.

Page 2: Mvc ASP.net q & a Series

Step 2:- Add controllerSo let’s go and add a new controller as shown in the below figure.

Once you add the new controller you should see some kind of code snippet as shown in the below snippet.public class Default1Controller : Controller{//// GET: /Default1/public ActionResult Index(){return View();}}Step 3:- Add ViewNow that we have the controller we need to go and add the view. So click on the Index function which is present in the control and click on add view menu as shown in the below figure.

Page 3: Mvc ASP.net q & a Series

The add view pops up a modal box to enter view name which will be invoked when this controller is called as shown in the figure below. For now keep the view name same as the controller name and also uncheck the master page check box.

Once you click on the ok button of the view, you should see a simple ASPX page with the below HTML code snippet. In the below HTML code snippet I have added “This is my first MVC application”.<html xmlns="http://www.w3.org/1999/xhtml" ><head runat="server"><title>Index</title></head><body><div>This is my first MVC application</div></body></html>Step 4:- Run the applicationIf you do a CNTRL + F5 you should see a error as shown in the below figure. This error is obvious because we have not invoked the appropriate controller / action.

Page 4: Mvc ASP.net q & a Series

If you append the proper controller on the URL you should be able to see the proper view.

2. How to pass data from controller to views? - Lab 2

Lab2:- Passing data between controllers and viewsThe controller gets the first hit and loads the model. Most of the time we would like to pass the model to the view for display purpose. As an ASP.NET developer your choice would be to use session variables, view state or some other ASP.NET session management object. 

The problem with using ASP.NET session or view state object is the scope. ASP.NET session objects have session scope and view state has page scope. For MVC we would like to see scope limited to controller and the view. In other words we would like to maintain data when the hit comes to controller and reaches the view and after that the scope of the data should expire.

Page 5: Mvc ASP.net q & a Series

That’s where the new session management technique has been introduced in ASP.NET MVC framework i.e. ViewData.

Step1:- Create project and set view dataSo the first step is to create a project and a controller. In the controller set the viewdata variable as shown in the below code snippet and kick of the view.public class DisplayTimeController : Controller{//// GET: /DisplayTime/

public ActionResult Index(){ViewData["CurrentTime"] = DateTime.Now.ToString();return View();}

}

Step 2:- Display view data in the view.

The next thing is to display data in the view by using the percentage tag. One important point to note is the view does not have a behind code. So to display the view we need to use the <%: tag in the aspx page as shown in the below code snippet.<body><div><%: ViewData["CurrentTime"] %></div></body>

3. Can we see a simple sample of model using MVC template? - Lab 3

Lab 3:- Creating a simple model using MVCIn this lab we will create a simple customer model, flourish the same with some data and display the same in a view.Step1:- Create a simple class fileThe first step is to create a simple customer model which is nothing but a class with 3 properties code, name and amount. Create a simple MVC project, right click on the model folder and click on add new item as shown in the below figure.

Page 6: Mvc ASP.net q & a Series

From the templates select a simple class and name it as customer.

Create the class with 3 properties as shown in the below the code snippet.public class Customer{private string _Code;private string _Name;private double _Amount;

public string Code{set{_Code = value;}get{return _Code;}}

public string Name{

Page 7: Mvc ASP.net q & a Series

get{return _Name;}set{_Name = value;}}

public double Amount{set{_Amount = value;}get {return _Amount;}}}

Step2:- Define the controller with actionThe next step is to add the controller and create a simple action display customer as shown in the below code snippet. Import the model namespace in the controller class. In the action we created the object of the customer class, flourished with some data and passed the same to a view named as “DisplayCustomer”public class CustomerController : Controller{…..….public ViewResult DisplayCustomer(){Customer objCustomer = new Customer();objCustomer.Id = 12;objCustomer.CustomerCode = "1001";objCustomer.Amount = 90.34;

return View("DisplayCustomer",objCustomer);}}

Step3:- Create strongly typed view using the class

Page 8: Mvc ASP.net q & a Series

We need to now join the points of MVC by creating views. So right click on the view folder and click add view. You should see a drop down as shown in the below figure. Give a view name, check create a strongly typed view and bind this view to the customer class using the dropdown as shown in the below figure.

The advantage of creating a strong typed view is you can now get the properties of class in the view by typing the model and “.” as shown in the below figure.

Page 9: Mvc ASP.net q & a Series

Below is the view code which displays the customer property value. We have also put an if condition which displays the customer as privileged customer if above 100 and normal customer if below 100.<body><div>The customer id is <%= Model.Id %> <br />

The customer Code is <%= Model.CustomerCode %> <br />

<% if (Model.Amount > 100) {%>This is a priveleged customer<% } else{ %>This is a normal customer<%} %>

</div></body>Step 4 :- Run your applicationNow the “D” thing, hit cntrl + f5 and pat yourself for one more lab success.

4. How can we create simple input screens using MVC template? - Lab 4

Lab 4:- Creating simple MVC data entry screenEvery project small or big needs data entry screens. In this lab we will create a simple customer data entry screen as shown in the below figure using MVC template. 

Page 10: Mvc ASP.net q & a Series

As soon as the end user enters details and submits data it redirects to a screen as shown below. If he entered amount is less than 100 it displays normal customer or else it displays privileged customer.

Step1:- Creating your data entry ASPX pageThe first step is to create the data entry page using the simple HTML form action tag as shown in the below code snippet. The most important point to note in the below code snippet is that the action is pointing to the controller action i.e ‘DisplayCustomer’.<form action="DisplayCustomer" method="post">Enter customer id :- <input type="text" name="Id" /> <br />Enter customer code :- <input type="text" name="CustomerCode" /><br />Enter customer Amount :-<input type="text" name="Amount" /><br /><input type="submit" value="Submit customer data" /></form>

Step2:- Creating the controller

Page 11: Mvc ASP.net q & a Series

The above defined form action will post to the controller class and on the function “DisplayCustomer”. So we need to get the data from the HTML controls, flourish the object and send the object to the view. 

Below is the code snippet of displaycustomer which flourishes the customer object by collecting data from request.form and sends the object to the view ‘displaycustomer.public class CustomerController : Controller{…..….[HttpPost]public ViewResult DisplayCustomer(){Customer objCustomer = new Customer();objCustomer.Id = Convert.ToInt16(Request.Form["Id"].ToString());objCustomer.CustomerCode = Request.Form["Id"].ToString();objCustomer.Amount = Convert.ToDouble(Request.Form["Amount"].ToString()); ;return View("DisplayCustomer", objCustomer);}}Step3:- Create the view to display the customer objectThe next step is to create the “DisplayCustomer” view.So right click on the view folder and click add view. You should see a drop down as shown in the below figure. Give a view name, check create a strongly typed view and bind this view to the customer class using the dropdown as shown in the below figure.

Page 12: Mvc ASP.net q & a Series

The advantage of creating a strong typed view is you can now get the properties of class in the view by typing the model and “.” as shown in the below figure.

Below is the view code which displays the customer property value. We have also put an if condition which displays the customer as privileged customer if above 100 and normal customer if below 100.<body><div>

Page 13: Mvc ASP.net q & a Series

The customer id is <%= Model.Id %> <br />

The customer Code is <%= Model.CustomerCode %> <br />

<% if (Model.Amount > 100) {%>This is a priveleged customer<% } else{ %>This is a normal customer<%} %>

</div></body>Step 4:- Finally run the projectFinal step is to run the project and see the output.

You should be also able to test above 100 and below 100 scenarios

Page 14: Mvc ASP.net q & a Series

5. How can we create MVC views faster and make them strong typed by using HTML helper? - Lab 5

Lab 5:- using HTML helper to create views fasterIn our previous lab we created a simple customer data entry screen. We completed the lab successfully but with two big problems:-• The complete HTML code was written manually. In other words, less productive. It’s like going back to dark ages where developers used to write HTML tags in notepad.<form action="DisplayCustomer" method="post">Enter customer id :- <input type="text" name="Id" /> <br />Enter customer code :- <input type="text" name="CustomerCode" /><br />Enter customer Amount :-<input type="text" name="Amount" /><br /><input type="submit" value="Submit customer data" /></form>• Added to it lot of manual code was also written in the controller to flourish the object and send data to the MVC view.public class CustomerController : Controller{…..….[HttpPost]public ViewResult DisplayCustomer(){Customer objCustomer = new Customer();objCustomer.Id = Convert.ToInt16(Request.Form["Id"].ToString());objCustomer.CustomerCode = Request.Form["Id"].ToString();objCustomer.Amount = Convert.ToDouble(Request.Form["Amount"].ToString()); ;return View("DisplayCustomer", objCustomer);}}Step 1:- Create the Customer classCreate a simple customer class , please refer Lab 5 for the same.Step2:- Creating the input HTML form using helper classesHTML helper classes have readymade functions by which you can create HTML controls with ease. Go to any MVC view and see the intellisense for HTML helper class you should see something as shown in the below figure.

Page 15: Mvc ASP.net q & a Series

By using HTML helper class you can create any HTML control like textbox, labels, list box etc just by invoking the appropriate function. 

In order to create the form tag for HTML we need to use “Html.BeginForm” , below goes the code snippet for the same.<% using (Html.BeginForm("DisplayCustomer","Customer",FormMethod.Post)) {%>-- HTML input fields will go here <%} %>The above code will generate the below HTML<form action="DisplayCustomer" method="post">…..…..</form>

The HTML helper “beginform” takes three input parameters action name (Method inside the controller), controller name (actual controller name) and HTTP posting methodology (Post or GET).

If you want to create a text box, simply use the “TextBox” function of html helper class as shown in the below code. In this way you can create any HTML controls using the HTML helper class functions.Enter customer id :- <%= Html.TextBox("Id",Model)%> <br />

The above code snippet will generate the below HTML code.Enter customer id :- <input type="text" name="Id" /> <br />To create a data entry screen like the one shown below we need to the use the below code snippet.

Page 16: Mvc ASP.net q & a Series

<% using (Html.BeginForm("DisplayCustomer","Customer",FormMethod.Post)){ %>Enter customer id :- <%= Html.TextBox("Id",Model)%> <br />Enter customer code :- <%= Html.TextBox("CustomerCode",Model) %><br />Enter customer Amount :- <%= Html.TextBox("Amount",Model) %><br /><input type="submit" value="Submit customer data" /><%} %>Step 3:- Create a strong typed view by using the customer class

So once you have created the view using the HTML helper classes it’s time to attach the customer class with view , please refer lab 5 for the same.Step4:- Creating the controller class.

The final thing is the controller code. The controller code now becomes very simple. The customer object will be auto flourished as we have used the HTML helper classes. You will create the controller class as we did in Lab 4 but we do not need to write any kind of code for connecting the HTML screens with controller, it’s all hidden and automated. [HttpPost]public ActionResult DisplayCustomer(Customer obj){return View(obj);}

Page 17: Mvc ASP.net q & a Series

Enjoy your output for different condition of customer amount entered.

6. What is MVC routing? - Lab 7

The functionality of routing is provided by classes in the assembly System.Web.Routing.dll.In this post I will discuss about the important classes and interfaces of the routing framework and steps in the process of creating an instance of the right controller from the URL pattern.

We have the System.Web.Routing.IRouteHandler interface (which inherits from IHttpHandler interface) defining the method System.Web.IHttpHandler GetHttpHandler(System.Web.Routing.RequestContext requestContext).The default route handler provided by the ASP.NET MVC framework which implements this interface isSystem.Web.Mvc.MVCRouteHandler.

This class instantiates the System.Web.Mvc.MVCHandler which in turn creates the controller instance via controller factory. The key entity class isSystem.Web.Routing.Route which inherits from System.Web.Routing.RouteBase class.This class is an abstraction of URL route.It stores the url pattern string,routing constraints and the reference to the route handler.There is another class System.Web.Routing.RouteData which stores the values obtained after parsing the url at runtime.This entire routing system is plugged into the ASP.NET pipeline via the System.Web.Routing.UrlRoutingModule which implements IHttpModule.

The basic steps in the routing process are as follows:

System.Web.Routing.RouteTable maintains a static reference to collection of Route objects.This is initialised in the Application_Start event.That's why in an ASP.NET MVC application project we can see the following lines of code by default added in global.asax.cs Application_Start event.

Page 18: Mvc ASP.net q & a Series

         RegisterRoutes(RouteTable.Routes);

         public static void RegisterRoutes(RouteCollection routes)         {             routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

            routes.MapRoute(                   "Default",                                              // Route name                   "{controller}/{action}/{id}",                           // URL with parameters                  new { controller = "Home", action = "Index", id = "" }  // Parameter defaults             );

       }

The UrlRouting module intercepts request.This is the also added by default in web.config of ASP.NET MVC application project as shown below:

         <add name="UrlRoutingModule" type="System.Web.Routing.UrlRoutingModule, System.Web.Routing,Version=3.5.0.0 ,Culture=neutral,   PublicKeyToken=31BF3856AD364E35"/>

The UrlRouting moduleo Creates the RouteData object by parsing the url.o The System.Web.Routing.RequestContext is created.This object maintains

reference to the HttpContext object ,RouteData and Route.o Invokes the GetHttpHandler method of the associated MVCRouteHandler

instance and passes the RequestContext object as parameter. MVCRouteHandler creates an instance of MVCHandler. MVCHandler

o Invokes the CreateController method of System.Web.Mvc.DefaultControllerFactory.This method creates the instance of System.Web.Mvc.IController type.

o Invokes the Execute method of IController instance.o Invokes the ReleaseController method

of System.Web.Mvc.DefaultControllerFactory.This method disposes the instance of the controller.