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:
 <div>    
  <% 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 =>      
      { %>   
       <td>   
        <%= Html.ActionLink("View Person", "ProductDetail", "Home", new { @id = m.ProductID.ToString() })%>         
         </td>   
      <% }); %>      
    <%}).Render(); %>   
  </div>   
and an action below:
Code:
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! :)
Greg

0 comments:

Post a Comment