Showing posts with label Json. Show all posts
Showing posts with label Json. Show all posts

Saturday, November 17, 2012

Custom Json Convertor For Nullable Integer Type in MVC

Introduction :

Before a Few Days, I had facing a one problem when I post data to controller in mvc using jquery and serialize data from json to model at that time it will give me give error like "Can not convert string to int".

The above problem generated due to, when I passing data as JavaScript object to controller at that time integer value passed as a blank. So it will consider that blank as string so not able to convert that string to int. But here I am little bit surprise when that model property is nullable type then also it will give me error like this instead of it should consider as null value.

After explore about this problem I got solution which is describe below with example.

Implementation :

To explain above problem I have taken examples of the student Information. First I have added Controller named Student Controller in MVC Application.

In Student Controller, I have added action name index which will return Index View. The controller code will look like below.

   public class StudentController : Controller
    {
        //
        // GET: / Student /

        public ActionResult Index()
        {
            return View();
        }
   }

After added action in controller, need to add model named Student. Model Class will look like below.

  public class Students
   {
      
        public int? StudentID{get;set;}
        public string StudentName;
        public string Address;
        public string City;
        public DateTime? BirthDate;
   }

After this, I have added view named Index.cshtml. Markup of View which is look like below.

@{
    ViewBag.Title = "Index";
}
<script src="@Url.Content("~/Scripts/jquery-1.7.1.min.js")"></script>
    
@model MvcApplication1.Students
<h2>Index</h2>
<table>
    
    <tr>
        <td>
            Student Name
        </td>
        <td>
            @Html.TextBoxFor(model=>model.StudentName)
        </td>
    </tr>
    <tr>
        <td>
            Address
        </td>
        <td>
            @Html.TextBoxFor(model=>model.Address)
        </td>
    </tr>
    <tr>
        <td>
            City
        </td>
        <td>
            @Html.TextBoxFor(model=>model.City)
        </td>
    </tr>
    <tr>
        <td>
            Student Marks
        </td>
        <td>
            @Html.TextBoxFor(model => model.StudentMarks)

        </td>
    </tr>
    <tr>
        <td>Birth Date</td>
        <td>
            @Html.TextBoxFor(model=>model.BirthDate)
        </td>
    </tr>
    <tr>
        <td colspan="2">
            <input type="button" onclick="SaveStudent()" value="SaveStudents"/>

        </td>

    </tr>
</table>

<script type="text/javascript">
    
    function SaveStudent() {
        var data = {
            StudentMarks: $('#StudentMarks').val(),
            StudentName: $('#StudentName').val(),
            Address: $('#Address').val(),
            City: $('#City').val(),
            BirthDate: $('#BirthDate').val()
        }
        $.ajax({
            type: 'POST',
            url: '/Student/SaveStudents',
            data:{Studentdata:JSON.stringify(data)},
            success: function (data) {
                alert("Student Saved Sucessfully");
            },
            dataType: 'JSON'
        });
    }

</script>

Now In a view, Save Student Button click, we are posting data using jquery to controller action named SaveStudent which will accept string as argument and serialize that json string into student model. The Saveaction method code is look like below.

  public JsonResult SaveStudents(string Studentdata)
  {
        Students obj = JsonConvert.DeserializeObject(Studentdata);
            
      return Json(new object { });
  } 

Now, run the application and try to save without enter data in student marks textbox. You will get below JsonReaderException.

Now, to resolve this exception we have two approaches,

In First approach, we are checking before send data to server, if marks field as blank then we passed as zero. This solution is only helpful when we have control to modify json. To implement this approach we need to modify save button JavaScript function which is described below.

  function SaveStudent() 
   {
      var StudentMarks=$('#StudentMarks').val();
      if(StudentMarks==’’)
      {
          StudentMarks=”0”;
      }
       var data = {
          StudentMarks: StudentMarks,
          StudentName: $('#StudentName').val(),
          Address: $('#Address').val(),
          City: $('#City').val(),
          BirthDate: $('#BirthDate').val()
        }
       $.ajax({
          type: 'POST',
          url: '/Student/SaveStudents',
          data:{Studentdata:JSON.stringify(data)},
          success: function (data) {
              alert("Student Saved Sucessfully");
          },
          dataType: 'JSON'
        });
    }

After above changes try to click save button you will get Message like Student Saved Successfully. Here we can check in firebug that Student marks passed as zero when marks field value is blank.

But what happen when we are received json from third party then we need to choose second approach.

In Second Approach, we are not going to change Json object which is passed into Jquery to controller. Here, Exception generates due to when it received blank value for Student Marks Field and it will not consider as a null but it will try converting that blank value into integer.

Now to resolve this issue, we need to define custom json convertor for the Student marks properties. For this, we need to add one class name integerJsonConverter which inherits from the JsonConverter class. Code of the integerJsonConverter is look like below.

public class integerJsonConverter: JsonConverter
    {

        public override bool CanConvert(Type objectType)
        {
            return objectType == typeof(int?);
        }

        public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
        {
            if (reader.TokenType == JsonToken.Null)
                return null;
            if (reader.TokenType == JsonToken.Integer)
                return reader.Value;

            if (reader.TokenType == JsonToken.String)
            {
                if (string.IsNullOrEmpty((string)reader.Value))
                    return null;
                int num;
                if (int.TryParse((string)reader.Value, out num))
                    return num;

                throw new JsonReaderException(string.Format("Expected integer, got {0}", reader.Value));
            }
            throw new JsonReaderException(string.Format("Unexcepted token {0}", reader.TokenType));
        }

        public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
        {
            writer.WriteValue(value);
        }
    }

JsonConverter Class has three abstract methods which we need to override in derived class. But here, needs to understand ReadJson Method is important.

In ReadJson method, we checked that if it will receive blank value for integer type field than need to consider as null. After adding above class, we need to change in student model class Student Marks Property. Here, we need to assign JsonConverter attribute which is type of integerJsonConverter. Which is look like below.

public class Students
    {
        [JsonConverter(typeof(integerJsonConverter))]
        public int? StudentMarks{get;set;}
        public string StudentName;
        public string Address;
        public string City;
        public DateTime? BirthDate;
  }

After defined, JsonConverter attribute for student marks, when it will serialize from json to model at that time it will use integerJsonConverter and consider blank value as null. Now run the application and check student Object after json serialize.

It will display null value for the Student Marks Properties.

Conclusion :

The goal of this article is just wants to show you that we can parse blank value as null for integer properties while serialize from json using custom json convertor. Hope this will help you.

Monday, November 28, 2011

Custom Action Method Selector in MVC

The default routing algorithm for how the ASP.NET MVC framework invokes actions is like {controller}/ {action}/ {id} patterns.

But this becomes more complex when you have two methods with the same name, or when you invoke an action when form data is submitted, or execute a method only when an AJAX request is made.

This can be done using ActionMethodSelector attributes. We generally use method selectors like:

  1. AcceptVerbs
  2. ActionName

AcceptVerbs :

This attribute is used when we want to execute some action when a particular HTTP operation is performed like POST, GET, DELETE, etc. E.g.:

[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Create(Employee employee)
{
      // To Do Code Here
}

The above method is executed when an HTTP POST operation is performed.

AcceptName :

This attribute is used when you expose an action name with a different name than its method name, or you can use an action name attribute to expose two methods with the same name as the action with different names. E.g.:

[ActionName(“Edit”)]
[AcceptVerbs(HttpVerbs.Get)]
public ActionResult Edit_GET(Employee  employee)
{
    // To Do Code Here
}
[ActionName(“Edit”)]
[AcceptVerbs(HttpVerbs.Post)]
Public ActionResult Edit_POST(Employee employee)
{
    // To Do Code Here
}

Custom Action Method Selector :

You can build your own ActionMethodSelector attributes by deriving from the abstract ActionMethodSelectorAttribute class.

This is an extremely simple class; you just need to override the method named IsValidForRequest (). If this returns false, this action method is not executed.

Now take a simple example of the Custom Action Method Selector. Develop an Ajaxmethod custom attribute useful for when you want to execute some action when an AJAX request is made.

The first step is to create an MVC application. Then add a class file named AjaxMethod.cs and inherit that class from ActionMethodSelectorAttribute. Then override a method named IsValidForRequest(). Your class will look like below:

public class AjaxMethod:ActionMethodSelectorAttribute
{
   public override bool IsValidForRequest(ControllerContext controllerContext, 
          System.Reflection.MethodInfo methodInfo)
   {
       return controllerContext.HttpContext.Request.IsAjaxRequest();
   }
}

In the IsValidForReuest method, we check the Request object for the AJAX request.

Now we can use the Ajaxmethod attribute in our controller when you want to execute some action only when an AJAX request comes. For this, add a controller named NewsController into the controller folder. In this controller, we define two index actions: first index action only executes when a page is posted back and the second action is invoked when an AJAX request comes. Your controller will look like below:

public class NewsController : Controller
{

    private readonly List _news = new List();
    private Random _rnd = new Random();

    public NewsController()
    {
        _news.Add("Moon Explodes");
        _news.Add("Stock Market up 200 percent");
        _news.Add("Talking Robort Created!");
    }
    //
    // GET: /News/

    public ActionResult Index()
    {
        var SelectedIndex = _rnd.Next(_news.Count);
        ViewData["News"] = _news[SelectedIndex];
        return View();
    }


    [AjaxMethod]
    [ActionName("Index")]
    public string Index_AJAX()
    {
        var SelectedIndex = _rnd.Next(_news.Count);
        return _news[SelectedIndex];
    }
}

Now add a View named index.aspx for displaying news and add the below markup into that:


    
      <%= Ajax.ActionLink("Get News", "Index", new AjaxOptions { UpdateTargetId = "news" })%>
      <%:ViewData["News"] %>

Now run the application. You will find that when the page loads the first time the first index action executes and when you click on the GetNews link at that time, the second index action executes. The first time, it will go check the Ajaxmethod attribute but the IsValidForRequest method will return false and then it will execute the first index action, but when you click on the link at that time, IsValidForRequest returns true and executes the second action.

Some of the least customized but very useful extension points in ASP.NET MVC are action method selector attributes. But using them, we can make seemingly complex things trivial.