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.

Now, let's add the necessary components for this route. First of all, create a class named EmployeeController in the /Controllers folder. You can do this by adding a new item to the project and selecting the MVC Controller Class template located under the Web | MVC category. Remove the Index action method, and replace it with a method or action named Show. This method accepts a firstname parameter and passes the data into the ViewData dictionary. This dictionary will be used by the view to display data.

The EmployeeController class will pass an Employee object to the view. This Employee class should be added in the Models folder (right-click on this folder and then select Add | Class from the context menu). Here's the code for the Employee class:

namespace MvcApplication1.Models
{
    public class Employee
    {
        public string FirstName { get; set; }
        public string LastName { get; set; }
        public string Email { get; set; }
    }

}

After adding the EmployeeController and Employee classes, the ASP.NET MVC project now appears as shown in the following screenshot:

The EmployeeController class now looks like this:

using System.Web.Mvc;
using
MvcApplication1.Models; 

namespace MvcApplication1.Controllers
{
    public class EmployeeController : Controller
    {
        public ActionResult Show(string firstname)
        {
            if (string.IsNullOrEmpty(firstname))
            {
                ViewData["ErrorMessage"] = "No firstname provided!";
            }
            else
            {
                Employee employee = new Employee
                {
                    FirstName = firstname,
                    LastName = "Example",
                    Email = firstname + "@example.com"
                };
                ViewData["FirstName"] = employee.FirstName;
                ViewData["LastName"] = employee.LastName;
                ViewData["Email"] = employee.Email;
            }
            return View();
        }
    }
}

Total Pages : 9 34567

comments