Showing posts with label View. Show all posts
Showing posts with label View. Show all posts

Saturday, November 14, 2009

Understanding MVC Views

We saw that MVC views are similar to traditional ASP.NET pages except that thay may not be correspondant to the url that the user types in the browser, meaning that if the user types [URL]/Account/MyAccount.aspx there must be an aspx page on the server named MyAccount.aspx under a folder named Account
In MVC it's different this page would be called Index.aspx placed under Views/Account
A view is a standard (X)HTML document that can contain scripts. You use scripts to add dynamic content to a view.
The listing below is the html of a view that has a label displaying the string "Hello"

<%@ 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>Demo page</title>
</head>
<body>
    <form id="form1" runat="server">
    
    <div>
        <asp:Label ID="Label1" runat="server" Text="Hello"></asp:Label>
    </div>
    </form>
</body>
</html>

If you want to display the current date and time you can use this:

<% Response.Write(DateTime.Now);%>

you can write any c# code inside the tags and display them like

<% int x = 5;
       int y = 2;
       int z = x + y;
       Response.Write(z);
    %>
which will display the number 7 on the page.
Instead of writing Response.Write() you can replace it with "=" sign
so writing
<% =DateTime.Now %>
will display the current DateTime

Using HTML Helper
HTML Helper is a function that generates a string of the markup of the some of the HTML (not ASP.NET controls) Controls to reduce the amount of HTML you write
the following code displays a text box on the page

<%
            using (Html.BeginForm())
            { %>
        <% =Html.TextBox("txtHello","This is a text box") %>
        <%}
        %>
this resmbles the following html

<input id="txtHello" name="txtHello" type="text" value="This is a text box" />
you can also use the HTML Helper class to produce other types of controlls. more info can be found in this link

View Data
Each Controller class has a property called ViewData
this property is used to pass data between the controller and the view. It is used in a way close to using
Session variables. It uses a Key-Value pair

The following code in the controller class adds a string to the View Data

ViewData["message"]="This is view data";
this code adds an entry with the key message and value This is view data to the ViewData of the view
In the view to display this string you write:

<%= Html.Encode(ViewData["message"]) %>
We use the HTML.Encode method to encode any special characters that can be there like > or <. You can pass any types in the ViewData cosider the following controller code:
ArrayList arr = new ArrayList();
            arr.Add("1");
            arr.Add("2");
            ViewData["message"] = arr;
            return View();
and the following View script

<% ArrayList temp =(ArrayList)ViewData["message"]; %>
       <%= temp[1] %>
this passes an arraylist to the view, then at the view it displays the second element of the arraylist

that was a quick explanation of the MVC View and how they interact with Controllers

Saturday, November 7, 2009

MVC Anatomy

In a previous post we saw how to create a Hello World MVC application.
Now we're going to perform an anatomy to this application to know what each part of the application exactly means.

First: Where is the Model, the View and the Controller ?
MVC Controller:
In tradotional asp.net the url you type corresponds to a page on the server, so when you request yoursite/abou.aspx there must be a page named about.aspx or a 404- page not found error is thrown.

In MVC it's different, there is no correspondance between the url you type and the pages that exist in the application. rather the url corresponds to a controller action than a page on the server.

The Controller is responsible for the way the user interacts with the application.
it manages the flow control logic of the application. It determines what response to make when the user makes a browser request.

The Controller is a C# class. Our Hello World application contains a controller class named HomeController.cs, It contains only one function named:public string Index()

public string Index()

{
return "Hello World";

}
this function is called when the user types URL /Home/Index in the browser cause as we said the controller functions respond to a user request.
Final thing to note that any public method contained in a controller is exposed as a controller action, meaning that it can be invoked by any user by typing it's name in the browser.
so if you have a function declared public as the following:

public void SomeFunction()







{



// Some Code



}

Any user can call this function by typing URL/Home/SomeFunction so be careful when declaring public functions in Controllers.

MVC View:
The view is equivalent to a page in t ASP.NET. It contains HTML markup that appears on the browser.
so for example if you want to create a page called demo , in Views folder create a subfolder named demo then in this subfolder create an aspx called Index.
then go to the Controllers folder and create a new controller with the name

DemoController.cs

in DemoController.cs add the following code


public ActionResult Index()
{
return View();
}

so when the user types url/demo the demo page is displayed
Notice that you must create the controller class in this form [ViewName]Controller.cs
MVC Model:
The MVC Model Contains you business logic, Validation logic or database access logic.
since that the Hello World application is not that complicated, there are no models in this application
Conclusion:
The view contains the logic for the interface, the Controller contains the logic for redirecting the user correctly to pages and respond to the user requests. And the Model contains the business or database access logic.
The Controller should contain minimal amount of code to handle user requests only.
If the Controller contains large bulks of code, consider removing some of them to a Model class in the Models folder