in

Chennai .Net User Group

A platform that enables you to Learn, Share & Grow (India's first .Net user group)

Shiju Varghese's Blog

February 2010 - Posts

  • QueryString values along with id parameter in ASP.NET MVC

     A number of folks have asked me how to pass query string values along with a route parameter id. They are looking onto send a url like  http://MySite/Home/Edit/5?name=shiju.

    The below is the routing configuration

     

    routes.MapRoute(

        "Default",                                            

        "{controller}/{action}/{id}",                        

        new { controller = "Home", action = "Index", id = UrlParameter.Optional }

    );

     

     

    We need to pass route information for id parameter and also attach query string values. The below is our action method

     

    public ActionResult Edit(int id,string name)

    {

        //To Do

        return View();

    }

     The below action method would set values for id parameter and query string parameter name.

    <%=Html.ActionLink("Edit","Edit",new { id=5,name="shiju"}) %>

    The ActionLink helper would generate the following markup

    <a href="/Home/Edit/5?name=shiju">Edit</a> 

     

    Our Action method would automatically taken the value 5 for id and value "shiju" for name. This is really nice feature and convention of ASP.NET MVC
  • ASP.NET MVC View Model object using C# 4 dynamic and ExpandoObject

     In my last post, I have explained the use of View Model objects in ASP.NET MVC applications. In this post, let me discuss on view model objects by using the C# 4 dynamic and ExpandoObject. I do not recommending to use dynamic keyword for creating View Model objects that will loss the intellisense feature of Visual Studio. 

     

    public ActionResult List() {

        dynamic viewModel = new ExpandoObject();

        viewModel.ContactGroup = contactRepository.ListGroups().ToSelectListItems(-1);

        return View(viewModel);

    }

     
    The above action method creating a view model object with dynamic keyword and dynamically add a property ContactGroup for binding values to a drop-down list. At compile time, an element that is typed as dynamic is assumed to support any operation. The ExpandoObject class enables you to add and delete members of its instances at run time and also to set and get values of these members.

     In our view page we are creating a strongly typed view with type dynamic

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

     

    The  Model.ContactGroup returns a type IEnumerable<SelectListItem> at runtime. Currently the HTML Helper Extension methods cannot be dynamically dispatched. So I am casting the ContactGroup property with IEnumerable<SelectListItem>.
     

     <%=Html.DropDownList("GroupId", Model.ContactGroup as IEnumerable<SelectListItem>)%>

     The purpose of the post is to explain the capabilities of dynamic keyword for creating strongly types views and  I do not recommending to use dynamic keyword for creating View Model objects. This will loss the  intellisense feature of Visual Studio and also affecting the maintainability. 

     

  • View Model pattern and AutoMapper in ASP.NET MVC Applications

    In real world ASP.NET MVC applications, we have to use model objects specially designed for our ASP.NET MVC views. Domain objects are designed for the needs for domain model and it is representing the domain of our applications. On the other hand, View Model objects designed for our needs for views.

    The below is the domain model of our demo

     



    We have a Contact domain entity that has a association with Contact Group. While we creating a new Contact, we have to specify that in which contactgroup belongs with the new contact.


    The below is the user interface for creating a new contact

     



    The above new contact UI has the form fields for representing the Contact entity and a GroupId field for representing the contact group.


    The below is the class for Contact View Model

     

    public class ContactViewModel

    {

    public int Id

    {

        get;

        set;

    }

    [Required(ErrorMessage = "FirstName Required")]

    [StringLength(25, ErrorMessage = "Must be less than 25 characters")]

    public string FirstName

    {

        get;

        set;

    }

    [Required(ErrorMessage = "LasttName Required")]

    [StringLength(25, ErrorMessage = "Must be less than 25 characters")]

    public string LastName

    {

        get;

        set;

    }      

     

    [Required(ErrorMessage = "Email Required")]

    [RegularExpression("^([0-9a-zA-Z]([-.\\w]*[0-9a-zA-Z])*@([0-9a-zA-Z][-\\w]*[0-9a-zA-Z]\\.)+[a-zA-Z]{2,9})$", ErrorMessage = "Not a valid email")]

    public string EMail

    {

        get;

        set;

    }

    [Required(ErrorMessage = "Phone Required")]

    public string Phone

    {

        get;

        set;

    }

    public string Address

    {

        get;

        set;

    }

    [Required(ErrorMessage = "GroupId Required")]     

    public int GroupId

    {

        get;

        set;

    }

    public IEnumerable<SelectListItem> ContactGroup

    {

        get;

        set;

    }

     

    }

     

    Our Contact View Model is designed for the purpose of View template and contains the all validation rules. It has properties for mapping values to Contact entity and a GroupId property for taking Id value from ContactGroup drop-down. And also providing a property ContactGroup for binding values to ContactGroup drop-down.

     The below code is Action method for Create Contact HttpGet request where we are creating an instance of Contact View Model and sets the Contactgroup property for binding values to drop-down list.

    /HttpGet for the Create Contact

    public ActionResult Create() {

        var viewModel = new ContactViewModel();

        var groups = contactRepository.ListGroups();

        viewModel.ContactGroup = groups.ToSelectListItems(-1);

        if (groups.Count<ContactGroup>() == 0)

            return RedirectToAction("Index", "Group");

        return View("Create", viewModel);

    }

     

      The below code is Action method for Create Contact HttpPost request.

    [HttpPost]

    public ActionResult Create(ContactViewModel contactToCreate) {

    if (ModelState.IsValid) {

     

        Contact newContact = new Contact();

        AutoMapper.Mapper.Map(contactToCreate, newContact);

        contactRepository.CreateContact(contactToCreate.GroupId, newContact);   

     }

    }

     

    In the above action method, our model binder is the ContactViewModel and we have to map values of ContactViewModel object to Domain model object Contact for the persistance purpose. In ASP.NET MVC applications, you have to map values between view model objects and domain model objects in many situations. In such scenarios, you can use AutoMapper for mapping values between objects to objects.In our code we copy values from our View model object ContactViewModel  to domain model object Contact. AutoMapper is a convention based object to object mapper framework developed by Jimmy Bogard. 

     A mapping configuration is a one time task and the below code setting map configuarion between our ContactViewModel and Contact.

    Mapper.CreateMap<ContactViewModel,Contact>();

    The below code copy values of ContactViewModel object to Contact object

    AutoMapper.Mapper.Map(contactToCreate, newContact);

     Check the Flattening for mapping to take a complex object model and flatten it to a simpler model. AutoMapper is available at http://automapper.codeplex.com/ and the source code is hosted at http://code.google.com/p/automapperhome.

  • My ASP.NET MVC 2 Talk at Community Tech Days

    I did a presentation titled " Building Apps with ASP.NET MVC 2 and Entity Framework" at Microsoft Community Tech Days. I have given a brief indroduction to ASP.NET MVC and demonstrated how to building applications with  ASP.NET MVC 2  and Entity Framework 4. You can download the powerpoint slide from here.

Copyright © 2002-2008 Chennai .Net User Group. All Rights Reserved. Microsoft and Microsoft logo's are trademarks of Microsoft Corporation