Thursday, February 7, 2013

Pass GUID as parameter to Action using ASP.NET MVC ContribGrid

Hi, In a scenario where in you want to pass a GUID object to an Action Parameter, the parameter might contain a null value. Since Guid is not nullable, you can't simply just pass it to an action parameter because Action parameters require nullable and reference types. You might encounter an error like this:
An optional parameter must be a reference type, a nullable type, or be declared as an optional parameter
Assuming you have an aspx view below:
  <% Html.Grid(Model).Columns   
    (c =>   
      c.For(m => m.Price);   
      c.For(m => m.ProductName);   
      c.For(m => m.ProductID);   
      c.For("View Person").Named("").Action(m =>      
      { %>   
        <%= Html.ActionLink("View Person", "ProductDetail", "Home", new { @id = m.ProductID.ToString() })%>         
      <% }); %>      
    <%}).Render(); %>   
and an action below:
public ActionResult ProductDetail(Guid id)   
   //do something here...where p is your product object   
   return View(p);   
Passing of guid as action parameter isn't possible. But here's a trick. You can substitute the ActionLink() with an HTML hyperlink tag and pass the Guid to the action.
       <a href="<%=Url.Action("ProductDetail","Home",new { @id = m.ProductID }) %>" >View Person</a>  
Cheers! :)


Post a Comment