FREE BOOK

Chapter 2: Your First ASP.NET MVC Application

Posted by Packt Publishing Free Book | ASP.NET MVC & JQuery August 12, 2009
This chapter describes the ASP.NET MVC project template that is installed in Visual Studio. A simple application is built, briefly touching on all of the aspects of the ASP.NET MVC framework.

The action method we've just created can be requested by a user via a URL-in this case, something similar to http://www.example.com/Employee/Maarten. This URL is mapped to the action method by the route we've created before. By default, any public action method (that is, a method in a controller class) can be requested using the default routing scheme. If you want to avoid a method from being requested, simply make it private or protected, or if it has to be public, add a [NonAction] attribute to the method.

Note that we are returning an ActionResult (created by the View() method), which can be a view-rendering command, a page redirect, a JSON result (discussed in detail in Chapter 8, AJAX and ASP.NET MVC), a string, or any other custom class implementation inheriting the ActionResult that you want to return. Returning an ActionResult is not necessary. The controller can write content directly to the response stream if required, but this would be breaking the MVC pattern-the controller should never be responsible for the actual content of the response that is being returned.

Next , create a Show.aspx page in the Views | Employee folder. You can create a view by adding a new item to the project and selecting the MVC View Content Page template, located under the Web | MVC category, as we want this view to render in a master page (located in Views | Shared). There is an alternative way to create a view related to an action method, which will be covered later in this chapter.

In the view, you can display employee information or display an error message if an employee is not found.

Add the following code to the Show.aspx page:

<%@ Page Title="" Language="C#" MasterPageFile="~/Views/Shared/Site.Master" AutoEventWireup="true" Inherits="System.Web.Mvc.ViewPage" %>

<asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server">
    <% if (ViewData["ErrorMessage"] != null) { %>
    <h1><%=ViewData["ErrorMessage"]%></h1>
    <% } else { %>
    <h1><%=ViewData["FirstName"]%> <%=ViewData["LastName"]%></h1>
    <p>
    E-mail: <%=ViewData["Email"]%>
    </p>
    <% } %>

</
asp:Content>

If the ViewData, set by the controller, is given an ErrorMessage, then the ErrorMessage is displayed on the resulting web page. Otherwise, the employee details are displayed.

Press the F5 button on your keyboard to start the development web server. Alter the URL in your browser to something ending in /Employee/Your_Name_Here, and see the action method and the view we've just created in action.

Total Pages : 9 45678

comments