Monday, January 2, 2012

Creating simple ASP.Net MVC 3 RAZOR application and adding a view to list users

I am really new to Razor the new view engine of ASP.Net MVC and decided to have a look at it during last weekend. First I started with what are the specialties of RAZOR and could see that it is more simple than the traditional ASP.Net view engine. Then I searched for the differences between the asp.net view engine and the Razor in terms of usage which will help me to write Razor view.Also I got the list which says how the Razor view elements are converted to HTML elements.

Seems we are ready to taste RAZOR through a sample application. Again searched for creating simple razor application and got the link which explains how to create a user list with option such as edit,list...
http://www.asp.net/mvc/tutorials/overview/creating-a-mvc-3-application-with-razor-and-unobtrusive-javascript

But it looks little complicated to me as we need to create model and all. So decided to just list down the user list from Membership provider.Steps goes as follows.
  1. Create a new ASP.Net MVC 3 project with default templates which will setup the membership provider and some pages such as the login, create new user etc...
  2. Create a new action in HomeController.cs named "Users". Add the below code to return the MembershipUserCollection.
    public ActionResult Users()
    {
          return View(Membership.GetAllUsers());
    }
  3. Right click on the "Users" Action method definition and select the "Add view".Use the same master page of other views(~/Views/Shared/_Layout.cshtml)
  4. Go to the added view and add the below lines in it.
    @{
        ViewBag.Title = "Users";
        Layout = "~/Views/Shared/_Layout.cshtml";
    }
    <h2>Users</h2>
    @foreach (var user in Model)
    { 
        @user.UserName
    }

  5. Go to master page and add action along with Home and About.
    <li>@Html.ActionLink("Users", "Users", "Home")</li>
Hope the steps are self explanatory. From the Action method in the Controller we are passing the MembershipUserCollection as model and that model is being enumerated in the RAZOR View to display the UserName.

More on ASP.Net MVC 3
http://msdn.microsoft.com/en-us/library/gg416514(v=vs.98).aspx
http://davidhayden.com/blog/dave/archive/2011/01/05/ASPNETMVC3TutorialsIndex.aspx

No comments: