Saturday, November 30, 2013

MVC: Passing C# enum collection as JSON object in model along with view



Okay...today I am gonna write about very weird requirement and a solution. I don't know how many of you already got into such scenario, but let's see what is it and then I would like to know if there is anything better.

What was my requirement?
Eternal question in developers' life, WHAT IS THE REQUIREMENT DUDE? And the answer is...

I had created a simple view using Razor syntax. I had created a model to bind it. I wanted to pass a collection of enum values to view and use that in JavaScript.
 Here is my model class
public class UserDetails
{
    public string UserName { get; set; }

    public string UserEmail { get; set; }

    public string City { get; set; }
}

To achieve my goal I added a property of type string to the model class and class looks like

public class UserDetails
{
     public string UserName { get; set; }

     public string UserEmail { get; set; }

     public string City { get; set; }

     public string Hobbies { get; set; }
}

Here is the enum of hobbies:
public enum Hobby : int
{
   Reading = 500,
   Writing,
   Sports,
   Music
} 

Action method looks like this:
public ActionResult GetUserDetails(int userId)
{
     // Get user details
     UserDetails userDetails = Utility.GetUserDetailsById(userId);
 

     //Get hobbies
     Collection<Hobby> hobbies = Utility.GetHobbiesByUserId(userId);
         

     // Create serializer object
System.Web.Script.Serialization.JavaScriptSerializer javaScriptSerializer = new System.Web.Script.Serialization.JavaScriptSerializer();

     // Serialize the object
     userDetails.HobbiesString = javaScriptSerializer.Serialize(hobbies);

     return View();
} 

Key line of code to notice here is use of JavaScriptSerializer. When I serialize the collection object using this serializer it returns serialized string. I set that to newly added property of type string and return view.
In view I get this string from the model object. To use it in JavaScript, I used JQuery’s parseJSON function as follows:
var hobbies = $.parseJSON('@Model.HobbiesString');

I got following array as a result:
[‘502’, ’503’, ‘504’]

Conclusion:
I learnt something new about use of JavaScript serializer. You can do fancy things using it. Do share your experiences too.
 
 
 
 
 
 


 
 

No comments:

Post a Comment