Showing posts with label MVC 3. Show all posts
Showing posts with label MVC 3. Show all posts

Friday, August 10, 2012

Master-detail with knockout in asp.net MVC 3

In this post we will be discussing creating a master detail relationship with Knockout.js in asp.net MVC 3. For this let’s take a simple view model like below-
    public class PersonViewModel
    {
        public int PersonID { get; set; }
        public string FirstName { get; set; }
        public string LastName { get; set; }
        public string Sex { get; set; }
        public int Age { get; set; }
        public string Address { get; set; }
    }
How we will be starting the problem is that, we will be retrieving a list of person with id, and name only and present the data in a HTML table. And on click of the table row we will be showing detail of the person with the additional information.

If we are not aware of knockout we can here and download and study the it.

For this example we will be using the following controller method to retrieve some in memory data-
public ActionResult Index()
{
    List<PersonViewModel> data = new List<PersonViewModel>();
    for (int i = 0; i < 10; i++)
        data.Add(new PersonViewModel() {PersonID=i, FirstName = "First Name " + i.ToString(), LastName = "Last Name " + i.ToString() });
    return View(data);
}
Next step is to prepare UI for the problem. First we will take the reference of jQuery and knockout file like below-
<script src="@Url.Content("~/Scripts/jquery-1.4.4.min.js")" type="text/javascript"></script>
<script src="http://knockoutjs.com/js/knockout-2.1.0.js" type="text/javascript"></script>
And we will be using the following HTML for displaying the person list and the detail-
<table>
    <tr><th>First Name</th><th>Last Name</th></tr>
    <tbody >
    <tr id="PersonID" style="cursor:pointer" >@*repeat the row to display all the person*@
        <td >First name of the person</td>
        <td >Last name of the person</td>
    </tr>
    </tbody>
</table>
<p data-bind="with: personViewModel.selectedItem">
    <b>Name:</b> <span >First name of the person</span> &nbsp;<span >Last name of the person</span><br />
    <b>Age:</b> <span >Age of the person</span> <br />
    <b>Sex:</b> <span >Sex of the person</span> <br />
    <b>Address:</b> <span >Address of the person</span> <br />
</p>
As you can see that the controller method is returning List<PersonModelView> as the type of the strongly type view, so, we will have the following model directive in the view-
@model List<KnockoutMasterDetail.Models.PersonViewModel>
This will give generic list of Person data. But as per out requirement of knockout we need to convert this list to JavaScript array. We can do this by the following code-
var persons = new Array();
@foreach (var d in Model)
{
    <text>persons.push({PersonID:</text>@d.PersonID<text>, FirstName:"</text>@d.FirstName<text>", LastName:"</text>@d.LastName<text>"});</text>
}
The above code will be inside the script tag in the view. And it’s simply looping the person list and creating an array of person object like {PersonID:1, FirstName:”First Name 1”, LastName:”Last name 1” }. Now we have our person array ready. Next let’s create view model to be used with knockout.
function personModel() {
    var self = this;
    self.persons = ko.observableArray(persons);
    self.selectedItem = ko.observable();
    self.getDetail = function(item) { 
      //to be implemented  
    }
}
personViewModel = new personModel();
In the above JavaScript function, we are adding this line self.persons = ko.observableArray(persons);. What it means is that we are directing the knockout that the persons array is an observable. That mean if there is any change in the array then its corresponding UI will also be changed automatically. For this example, if we do not make the array as observable, it will work as we are not expecting any change in the array. So, we can simply have self.persons = persons;. But we need the next statement, as on clicking a row we need to change the detail. To activate the viewmodel to work with knockout, we need to register the viewmodel. We can do this by the following like-
ko.applyBindings(personViewModel);
Just this registration will not work. We need to make the necessary changes in the HTML.

Now self.persons is an array and we need to make changes in the HTML table to link this array to the HTML table. We can do this by following-
    <tbody data-bind="foreach: personViewModel.persons">
    <tr data-bind="click:personViewModel.getDetail, attr: {id: PersonID}" style="cursor:pointer" >
        <td data-bind="text: FirstName"></td>
        <td data-bind="text: LastName"></td>
    </tr>
    </tbody>
What we are doing here is adding data-bind attribute that is related to knockout. Whenever we will make any change in the array, knockout will use this attribute to make changes back to the UI. In the first line we are using foreach to loop through all the items of the array persons and putting the values of the array item to row. Next line we have click:personViewModel.getDetail, attr: {id: PersonID}. In first part of it we are associating click event of the row to a function in the viewmodel named getDetail. In the second part we are assigning id of the row to PersonID. And in the remaining two lines we are assigning first name and last name to two cells.

Next we need to modify the detail section and we need to associate this to observable selectedItem in the model and we can do this by altering the HTML as below-
<p data-bind="with: personViewModel.selectedItem">
    <b>Name:</b> <span data-bind="text: FirstName"></span> &nbsp;<span data-bind="text: LastName"></span><br />
    <b>Age:</b> <span data-bind="text: Age"></span> <br />
    <b>Sex:</b> <span data-bind="text: Sex"></span> <br />
    <b>Address:</b> <span data-bind="text: Address"></span> <br />
</p>
So, now whenever we will click the row it will call the function getDetail in the model. Currently the function is empty. Let’s first have a controller method that returns the detail of the person like below-
        public JsonResult GetDetail(int personID)
        {
            return Json(new PersonViewModel()
            {
                FirstName = "FirstName " + personID.ToString(),
                LastName = "LastName " + personID.ToString(),
                Sex = "Sex " + personID.ToString(),
                Age = personID,
                Address = "Address " + personID.ToString()
            });
        }
Here we are just building an in memory detail. And we can call the controller method like-
    self.getDetail = function(item) { 
        $.ajax({
            url:  '@Url.Action("GetDetail","Person")',
            data: { personID: item.PersonID },
            type: "POST",
            success: function (response) {
                self.selectedItem(response); 
            },
            error:function(x,y,z){debugger;}
        });
    }
Inside the success method we are getting the result of the ajax call and assigning the result to the selectedItem(self.selectedItem(response);). As it’s an observable, knockout will automatically update the corresponding HTML for detail. That’s all. You can download the source code from this link.

Wednesday, June 13, 2012

Passing extra parameters with dataTable.net plugin while server paging is enabled in asp.net MVC 3 and Web form

Recently I have added two posts to implement dataTable.net jQuery plugin with server side paging with MVC3 and asp.net web form. First one is in MVC 3 and second one is in web form. We can find these two posts here-

http://growingtech.blogspot.in/2012/06/ajax-data-paging-with-datatablesnet.html
http://growingtech.blogspot.in/2012/06/ajax-data-paging-with-datatablesnet_06.html

I will request to study these two posts in sequentially to understand this one.

In this post we will be discussing how to pass additional parameters when page index changes happen in dataTable.net. To pass additional parameters in ajax paging we can use fnServerParams function of dataTable. In the MVC post we have discussed how dataTable plugin adds request parameters as querystring. And this function (fnServerParams) provides an input parameter which is nothing but an array of the query string parameters. We can do modification to the array in the function to accomodiate our need of extra parameters. Each array element in the input array is an object of the following form-
{ "name": "name of parameter/querystring", "value": "value of parameter/querystring " }
So, we can add our additional parameter accordingly. Suppose we have following input data as additional parameter-
First Criteria: <input id="txtParameter1" /><br />
Second Criteria : <input id="txtParameter2" />
We can add the these extra parameter like below-
<script type="text/javascript" charset="utf-8">
    $(document).ready(function () {
        $('#example').dataTable({
            "bServerSide": true,
            "bProcessing": true,
            "sPaginationType": "full_numbers",
            "sAjaxSource": 'Datatable Plugin Pagination Issue AjaxPath.aspx',
            "fnServerParams": function (aoData) {
                aoData.push(
                    { "name": "firstcriteria", "value": $("#txtParameter1").val() },
                    { "name": "secondcriteria", "value": $("#txtParameter2").val() }
                );
            }
        });
    });
</script>
In web form:

In web form we can access these parameters like below and use for database operations –
var firstCriteria = Request.QueryString["firstcriteria"];
var secondCriteria = Request.QueryString["secondcriteria"];
In MVC 3-

To use in MVC 3 we can modify data model like below to accommodate our new parameters-
    public class TableParameter
    {
        public string sEcho { get; set; }
        public int iDisplayStart { get; set; }
        public int iDisplayLength { get; set; }
        public string firstcriteria { get; set; }
        public string secondcriteria { get; set; }
    }
Input data will be available in the controller method to use.

Wednesday, June 6, 2012

jqPlot bar graph with asp.net MVC 3

In this post we will be exploring using jqPlot bar graph with asp.net MVC 3. We can download the plugin for the below location-

http://www.jqplot.com/

To start with let’s see how bar graph works. Following is code for a bar graph with HTML and JavaScript bar data object-
<link class="include" rel="stylesheet" type="text/css" href="@Url.Content("~/scripts/jqplot/css/jquery.jqplot.min.css")" />
<!--[if lt IE 9]><script language="javascript" type="text/javascript" src="@Url.Content("~/scripts/jqplot/excanvas.min.js")"></script><![endif]-->
<script type="text/javascript" src="@Url.Content("~/scripts/jqPlot/jquery.jqplot.min.js")"></script>
@*<script type="text/javascript" src="@Url.Content("~/scripts/jqplot/jqplot.canvasTextRenderer.min.js")"></script>
<script type="text/javascript" src="@Url.Content("~/scripts/jqplot/jqplot.canvasAxisTickRenderer.min.js")"></script>*@
<script type="text/javascript" src="@Url.Content("~/scripts/jqplot/jqplot.categoryAxisRenderer.min.js")"></script>
<script type="text/javascript" src="@Url.Content("~/scripts/jqPlot/jqplot.barRenderer.min.js")"></script>

<div class="example-content">
    <!-- Example scripts go here -->
    <style type="text/css">
        .jqplot-target
        {
            margin: 30px;
        }
        .tooltipCss
        {
            position: absolute;
            background-color: #b2b1ac;
            color: White;
            z-index: 200;
            padding: 5px;
            border-radius: 5px;
            display: none;
        }
    </style>
    <div id="chart2" class="plot" style="width: 760px; height: 360px;">
    </div>
</div>
<script language="javascript" type="text/javascript">
    $(document).ready(function () {
        pop1980 = [4, 5, 3, 6, 5, 4, 2, 5];
        pop1990 = [3, 5, 6, 2, 4, 3, 4, 6];
        pop2000 = [2, 5, 6, 3, 4, 5, 2, 4];
        pop2008 = [5, 3, 4, 2, 6, 5, 2, 4];

        ticks = [5, 6, 7, 8, 9, 10, 11, 12];

        series = [
                  { label: 'r. DMR Published - Singapore' },
                  { label: 's. DMR Published - London' },
                  { label: 't. DMR Published - Houston' },
                  { label: 'u. DMR Published - Global' }
               ];

        plot2 = $.jqplot('chart2', [pop1980, pop1990, pop2000, pop2008], {
            legend: {
                show: true,
                placement: 'outsideGrid'
            },
            seriesDefaults: {
                renderer: $.jqplot.BarRenderer,
                rendererOptions: {
                    barPadding: 5
                }
            },
            series: series,
            axes: {
                xaxis: {
                    renderer: $.jqplot.CategoryAxisRenderer,
                    ticks: ticks
//                    ,
//                    tickRenderer: $.jqplot.CanvasAxisTickRenderer,
//                    tickOptions: {
//                        angle: -15
//                    }
                }
            }
        });
        $('#chart2').bind('jqplotDataMouseOver',
            function (ev, seriesIndex, pointIndex, data) {
                $('#info2').html('series "' + series[seriesIndex].label + '" point "' + (pointIndex + 5) + '"<br /> value "' + data[1] + '"');
                $('#info2').css({ "left": ev.pageX + 3, "top": ev.pageY })
                $('#info2').show();
            }
        );
        $('#chart2').bind('jqplotDataUnhighlight',
            function (ev) {
                $('#info2').hide();
            }
        );
    });
</script>
<div id="info2" class="tooltipCss">
</div>
If you check the file references, you can check a file named excanvas.min.js. This is the file for internet explorer less than 9. As the bar is rendered in canvas, a HTML 5 feature, which is not supported in lower versions of IE. All other files are required for bar graph. If you notice, you can see there are two files that are commented out (jqplot.canvasTextRenderer.min.js and jqplot.canvasAxisTickRenderer.min.js ). These two files are needed if you want to rotate the tick texts in both the axis. In the bar initialization you can find the corresponding tickRenderer code is commented out for x-axis. Div with id chart2 is used to hold the bar graph. And div with id info2 is used to hold tooltip content. Input to the graph is array of arrays where each inner array represents data for each bar.

Number of items in each inner array is same. Other than this array there are two more arrays used. One is ticks, this is used to represent the data interval in x- axis. And another is series, this array is used to represent the name of each bar. The order of the series item should be same as the order of the data input arrays.

There are many options used in the plugin. Detail of various options can be found here-

http://www.jqplot.com/docs/files/jqPlotOptions-txt.html
http://www.jqplot.com/docs/files/optionsTutorial-txt.html

We can use as many options required in this case.

Other than these we are using two more events in the plugin named 'jqplotDataMouseOver' and 'jqplotDataUnhighlight'. We are using these events to track tooltips in each bar. We can add debugger and check what is happening.

Model driven Bar Graph:

To make the graph model driven we can have the following model-
namespace Bar.Models
{
    public class BarViewModel
    {
        public int Id { get; set; }
        public string BarName { get; set; }
        public int[] Values { get; set; }
    }
    public class BarDataViewModel
    {
        public int[] TickValues { get; set; }
        public List<BarViewModel> Data { get; set; }
    }
}
And in the controller action we are creating the data in memory as –
        public ActionResult ModelDrivenBar()
        {
            BarDataViewModel data = new BarDataViewModel();
            data.Data = new List<BarViewModel>();
            BarViewModel bar;
            Random r=new Random();
            for (int i = 0; i < 4; i++)
            {
                bar = new BarViewModel();
                bar.Id = i;
                bar.BarName = "Bar Name " + i.ToString();
                bar.Values = new int[10];
                for (int j = 0; j < 10; j++)
                    bar.Values[j] = r.Next(2, 6);
                data.Data.Add(bar);
            }
            data.TickValues = new int[10];
            for (int i = 5; i < 15; i++)
                data.TickValues[i - 5] = i;
            return View(data);
        }
We need to do two changes in the view to accommodate the changes. First add the following line at the starting of the view-
@model Bar.Models.BarDataViewModel
And secondly generate the three arrays, as we have discussed earlier, like below-
        var data = new Array();
        var ticks = new Array();
        var series = new Array();
        @foreach (var d in Model.TickValues)
        {
            <text>ticks.push(</text>@d<text>);</text>
        }
        @foreach (var d in Model.Data)
        {
            <text>var bar</text>@d.Id<text>= new Array();</text>
            <text>series.push({label : "</text>@d.BarName<text>"});</text>
            foreach (var darray in d.Values)
            { 
                <text>bar</text>@d.Id<text>.push(</text>@darray<text>);</text>
            }
            <text>data.push(bar</text>@d.Id<text>);</text>
        }
        plot2 = $.jqplot('chart2', data, {
Instead of explaining the code above, we can check the output of the code below-
        var data = new Array();
        var ticks = new Array();
        var series = new Array();
            ticks.push(5);
            ticks.push(6);
            ticks.push(7);
            ticks.push(8);
            ticks.push(9);
            ticks.push(10);
            ticks.push(11);
            ticks.push(12);
            ticks.push(13);
            ticks.push(14);
            var bar0= new Array();
            series.push({label : "Bar Name 0"});
                bar0.push(2);
                bar0.push(4);
                bar0.push(5);
                bar0.push(5);
                bar0.push(4);
                bar0.push(3);
                bar0.push(2);
                bar0.push(2);
                bar0.push(3);
                bar0.push(5);
            data.push(bar0);
            var bar1= new Array();
            series.push({label : "Bar Name 1"});
                bar1.push(4);
                bar1.push(2);
                bar1.push(2);
                bar1.push(5);
                bar1.push(2);
                bar1.push(3);
                bar1.push(4);
                bar1.push(5);
                bar1.push(5);
                bar1.push(2);
            data.push(bar1);
            var bar2= new Array();
            series.push({label : "Bar Name 2"});
                bar2.push(4);
                bar2.push(3);
                bar2.push(3);
                bar2.push(4);
                bar2.push(2);
                bar2.push(2);
                bar2.push(2);
                bar2.push(3);
                bar2.push(4);
                bar2.push(5);
            data.push(bar2);
            var bar3= new Array();
            series.push({label : "Bar Name 3"});
                bar3.push(5);
                bar3.push(4);
                bar3.push(5);
                bar3.push(2);
                bar3.push(4);
                bar3.push(3);
                bar3.push(5);
                bar3.push(4);
                bar3.push(3);
                bar3.push(5);
            data.push(bar3);
        plot2 = $.jqplot('chart2', data, {
What we are doing here is just creating the bar data dynamically by looping the model data.

Ajax Bar Graph:

To make it ajax driven we can simply change the controller return type like below-
        public JsonResult AjaxBarData()
        {
            //same code like earlier
            return Json(data,JsonRequestBehavior.AllowGet);
        }
And we can do an ajax call to the controller and in the success of the ajax call we can initialize the graph-
<script type="text/javascript">
    $(document).ready(function () {
        $.ajax({
            type: "get",
            timeout: 30000,
            url: '@Url.Action("AjaxBarData")',
            dataType: "json",
            contentType: "application/json; charset=utf-8",
            success: function (result) {
                var data = new Array();
                var ticks = new Array();
                var series = new Array();
                $(result.TickValues).each(function (i, itm) {
                    ticks.push(itm);
                });
                $(result.Data).each(function (i, itm) {
                    series.push({ label: itm.BarName });
                    data[i] = new Array();
                    $(itm.Values).each(function (j, item) {
                        data[i].push(item);
                    });
                });
  //initialize the bar graph here
                plot2 = $.jqplot('chart2', data, {
            },
            error: function (req, status, error) {
                debugger;
            }
        });
    });
</script>
That’s all. You can download the bar code here.

Tuesday, June 5, 2012

jqPlot Line with asp.net MVC 3

In this post we will be exploring using jqPlot line graph with asp.net MVC 3. Before starting with MVC, let’s see how line graph works. Let’s first download the plugin from-

http://www.jqplot.com/

To start with let’s see how line graph works. First let’s include the following file references-
<link class="include" rel="stylesheet" type="text/css" href="@Url.Content("~/scripts/jqplot/css/jquery.jqplot.min.css")" />
<!--[if lt IE 9]><script language="javascript" type="text/javascript" src="@Url.Content("~/scripts/jqplot/excanvas.min.js")"></script><![endif]-->
<script type="text/javascript" src="@Url.Content("~/scripts/jqPlot/jquery.jqplot.min.js")"></script>
<script type="text/javascript" src="@Url.Content("~/scripts/jqplot/jqplot.canvasTextRenderer.min.js")"></script>
<script type="text/javascript" src="@Url.Content("~/scripts/jqplot/jqplot.canvasAxisTickRenderer.min.js")"></script>
<script type="text/javascript" src="@Url.Content("~/scripts/jqplot/jqplot.dateAxisRenderer.min.js")"></script>
@*<script type="text/javascript" src="@Url.Content("~/scripts/jqplot/jqplot.highlighter.min.js")"></script>*@
For this demo we are going to use the following CSS-
<style type="text/css">
    .jqplot-point-label
    {
        white-space: nowrap;
    }
    div.jqplot-target
    {
        height: 400px;
        width: 750px;
        margin: 70px;
    }
    .tooltipCss
    {
        position: absolute;
        background-color: #b2b1ac;
        color: White;
        z-index: 200;
        padding: 5px;
        border-radius: 5px;
        display: none;
    }
</style>
Following is the code used to activate the line plugin-
<script type="text/javascript">
    $(document).ready(function () {
        var line1 = [['2/2/2008', 10], ['2/5/2008', 56], ['2/7/2008', 39], ['2/10/2008', 81], ['2/15/2008', 10], ['2/18/2008', 56], ['2/22/2008', 39], ['2/30/2008', 81]];
        var line2 = [['2/16/2008', 43], ['2/18/2008', 45], ['2/17/2008', 50], ['2/12/2008', 40], ['2/1/2008', 10], ['2/14/2008', 56], ['2/7/2008', 39], ['2/22/2008', 81], ['2/29/2008', 81]];
        var labels = [
                   { label: 'serie name 1', lineWidth: 1 },
                   { label: 'serie name 2', lineWidth: 1 }
                ];

        var plot2 = $.jqplot('chart1', [line1, line2], {
            series: labels,
            legend: {
                show: true,
                placement: 'outsideGrid'
            },
            //                highlighter: {
            //                    show: true,
            //                    showTooltip: true,
            //                    yvalues: 2,
            //                    formatString: '<table class="jqplot-highlighter"><tr><td>Point </td><td>"%s"</td></tr><tr><td>value </td><td>"%s"</td></tr><tr><td>Series </td><td>"%s"</td></tr></table>'
            //                },
            cursor: {
                show: true,
                tooltipLocation: 'sw'
            },
            axes: {
                xaxis: {
                    tickRenderer: $.jqplot.CanvasAxisTickRenderer,
                    renderer: $.jqplot.DateAxisRenderer,
                    label: 'Date',
                    tickOptions: {
                        angle: -15,
                        formatString: '%m/%d/%y'
                    }
                },
                yaxis: {
                    label: 'Value',
                    labelRenderer: $.jqplot.CanvasAxisLabelRenderer
                }
            }
        });

        $('#chart1').bind('jqplotDataMouseOver',
                    function (ev, seriesIndex, pointIndex, data) {
                        date = new Date(data[0]);
                        $('#info2').html('series "' + labels[seriesIndex].label + '" point "' + (date.getMonth() + 1) + "/" + (date.getDate() < 10 ? "0" + date.getDate() : date.getDate()) + "/" + date.getFullYear() + '"<br /> value "' + data[1] + '"');
                        $('#info2').css({ "left": ev.pageX + 3, "top": ev.pageY })
                        $('#info2').show();
                    }
                );
        $('#chart1').bind('jqplotDataUnhighlight',
                    function (ev) {
                        $('#info2').hide();
                    }
            );
    });
</script>
<div class="example-content">
    <div class="example-plot" id="chart1">
    </div>
</div>
<div id="info2" class="tooltipCss">
</div>
Here I am not going to explain the detail of the plugin. There are many options used in the plugin. Detail of various options can be found here-

http://www.jqplot.com/docs/files/jqPlotOptions-txt.html
http://www.jqplot.com/docs/files/optionsTutorial-txt.html

And we can use the options whatever serves our purpose. You can see some commented code in the plugin that is highlighter. There are many options available in the highlighter, but managing the tooltip HTML is not that great. So, I wish to use separate highlighter.

I have used the div with id info2 to hold the tooltip content. As you can, two events are attached to the plugin 'jqplotDataMouseOver' and 'jqplotDataUnhighlight' to deal with tooltip on the points on the line graph. First one is used for mouse over and the second one is used for mouse out.

If we check the input data to the plugin is nothing but an array of lines where each line is in turn array of points. Each point is intern is an array of two elements. First one is date and second is the value for that date.

So, if we want to implement using MVC is nothing but returning this data array. Also as you can see that we have used a separate array named labels to hold the names of the lines.

Model driven Line:

Let’s implement it with MVC 3. To start with let’s have the following model-
namespace Line.Models
{
    public class LineViewModel
    {
        public int id { get; set; }
        public string LineName { get; set; }
        public List<LineDataViewModel> data { get; set; } 
    }
    public class LineDataViewModel
    {
        public DateTime Date { get; set; }
        public double Value { get; set; }
    }
}
Everything is same as previous implementation except the data creation. Let’s first replace the first line of the plugin initialization by the following line-
var plot2 = $.jqplot('chart1', line, {
And also the view should accept the following model-
@model  List
Let’s now build the data array "line" and series "labels". Now gets generate some random data in action method and pass to the view like below-
        public ActionResult ModelDrivenLine()
        {
            Random r = new Random();
            List<LineViewModel> data = new List<LineViewModel>();
            
            LineViewModel l1 = new LineViewModel();
            l1.LineName = "First line";
            l1.id = 1;
            l1.data = new List<LineDataViewModel>();
            for (int i = 0; i < 10; i++)
                l1.data.Add(new LineDataViewModel() { Date = DateTime.Now.AddDays(r.Next(1, 25)), Value = r.Next(1, 10) });
            data.Add(l1);

            LineViewModel l2 = new LineViewModel();
            l2.LineName = "Second line";
            l2.id = 2;
            l2.data = new List<LineDataViewModel>();
            for (int i = 0; i < 10; i++)
                l2.data.Add(new LineDataViewModel() { Date = DateTime.Now.AddDays(r.Next(1, 25)), Value = r.Next(1, 10) });
            data.Add(l2);

            return View(data);
        }
Now we can generate the data by the following code-
        var line = new Array();
        var labels = new Array();
        @foreach (var m in Model)
        {
            <text>labels.push({label: "</text>@m.LineName<text>"}); 
            var line</text>@m.id<text> =new Array();</text>
            foreach (var l in m.data)
            {
                <text> line</text>@m.id<text>.push(["@l.Date.ToString("M/dd/yyyy")", @l.Value]);</text>
            }
            <text>line.push(line</text>@m.id<text>);</text>
        }
What we are doing is looping the model data and creating two required array. Here <text></text> is used to direct the razor engine to render the data as text. Line <text>labels.push({label: "</text>@m.LineName<text>"}); is used to create series name (the array for name of the lines(labels)). If you see the model there is a separate property as Id. This is used to uniquely identify each line. And you can see in line var line</text>@m.id<text> =new Array();</text> we are creating array for each line, so if id is one, the result of the line will be var line1 =new Array();. And with the next for loop we are pushing the line values to the corresponding array. And the next line we are adding the array to the final data array. That's all.

The result of the above code will look like-
        var line = new Array();
        var labels = new Array();
            labels.push({label: "First line"}); 
            var line1 =new Array();
                 line1.push(["6/21/2012", 2]);
                 line1.push(["6/15/2012", 8]);
                 line1.push(["6/06/2012", 9]);
                 line1.push(["6/13/2012", 2]);
                 line1.push(["6/09/2012", 2]);
                 line1.push(["6/15/2012", 8]);
                 line1.push(["6/09/2012", 5]);
                 line1.push(["6/13/2012", 8]);
                 line1.push(["6/23/2012", 5]);
                 line1.push(["6/12/2012", 1]);
            line.push(line1);
            labels.push({label: "Second line"}); 
            var line2 =new Array();
                 line2.push(["6/11/2012", 9]);
                 line2.push(["6/27/2012", 2]);
                 line2.push(["6/27/2012", 6]);
                 line2.push(["6/21/2012", 5]);
                 line2.push(["6/13/2012", 6]);
                 line2.push(["6/08/2012", 5]);
                 line2.push(["6/07/2012", 7]);
                 line2.push(["6/18/2012", 8]);
                 line2.push(["6/19/2012", 7]);
                 line2.push(["6/15/2012", 6]);
            line.push(line2);
        var plot2 = $.jqplot('chart1', line, {
Now if we want to use jQuery ajax to get data from the controller action and use it to the line graph. We can do it simply. We can have a view from the view we can do an ajax call to controller action. And the action method goes like below-
        public JsonResult AjaxLineJSON()
        {
            //This part is just like the previous action method
            return Json((from d in data
                select new {d.LineName,data= (from tl in d.data
                                         select new { Date= tl.Date.ToString("M/dd/yyyy"), Value=tl.Value}).ToList()}), JsonRequestBehavior.AllowGet);
        }
And the ajax call looks like-
<script type="text/javascript">
    $(document).ready(function () {
        $.ajax({
            type: "get",
            timeout: 30000,
            url: '@Url.Action("AjaxLineJSON")',
            dataType: "json",
            contentType: "application/json; charset=utf-8",
            success: function (result) {
                var line = new Array();
                var series = new Array();
                $(result).each(function (i, itm) {
                    series.push(itm.LineName);
                    line[i] = new Array();
                    $(itm.data).each(function (j, item) {
                        line[i].push([item.Date, item.Value])
                    });
                });
                //initialize the graph here.
        });
    });
</script>
That is all for now. You can download the code from here.

Sunday, June 3, 2012

Ajax data paging with dataTables.net jQuery plugin in asp.net MVC 3

In this post we will be discussing how to do ajax based server side data paging with dataTables.net jQuery plugin in asp.net MVC 3. To continue this lets check following post –

http://datatables.net/examples/data_sources/ajax.html

This is a basic way to access ajax data paging. In this sample all the data needed is retrieved and paging is done in browser memory. But we need more sophisticated approach. That is separate ajax call for each page index change. We can follow the following post for this-

http://datatables.net/examples/data_sources/server_side.html

This is a PHP based code. Let’s do in MVC. Before starting, let’s do some background study on the same.

First case: Let’s see the request on the IE developer tool network tab. If we visit request header and request value we can get data like below-

/examples/examples_support/server_processing.php?sEcho=1&iColumns=5&sColumns=&iDisplayStart=0&iDisplayLength=10&mDataProp_0=0&mDataProp_1=1&mDataProp_2=2&…………….. The bolded text query strings are the required ones. The additional query string can be used are we need but these are out of scope for the current sample.

Second case: Now let’s go to the Response Body. We can get the result like below-

{"sEcho": 1, "iTotalRecords": 57, "iTotalDisplayRecords": 57, "aaData": [ ["Gecko","Firefox 1.0","Win 98+ / OSX.2+","1.7","A"],["Gecko","Firefox 1.5","Win 98+ / OSX.2+","1.8","A"],["Gecko","Firefox 2.0","Win 98+ / OSX.2+","1.8","A"],["Gecko","Firefox 3.0","Win 2k+ / OSX.3+","1.9","A"],["Gecko","Camino 1.0","OSX.2+","1.8","A"],["Gecko","Camino 1.5","OSX.3+","1.8","A"],["Gecko","Netscape 7.2","Win 95+ / Mac OS 8.6-9.2","1.7","A"],["Gecko","Netscape Browser 8","Win 98SE+","1.7","A"],["Gecko","Netscape Navigator 9","Win 98+ / OSX.2+","1.8","A"],["Gecko","Mozilla 1.0","Win 95+ / OSX.1+","1","A"]] }

Here we can see that it returning the sEcho, iTotalRecords, iTotalDisplayRecords, aaData where first three values are integer type and last one is the array of data rows. We can visualize this in the image below-



Now if we think this in terms of MVC model binding things will get clear. We can use a model data class that except the required input parameters and return a JSON result of the desired format. Lets start with the source code-

ViewModel-
    public class TableParameter
    {
        public string sEcho { get; set; }
        public int iDisplayStart { get; set; }
        public int iDisplayLength { get; set; }
    }
In case of the parameter we are using only three here as explained in the first case. We can use other parameters as per our need.

View-
@{
    ViewBag.Title = "Pagination_With_Data_Table_issue";
    Layout = "~/Views/Shared/_Layout.cshtml";
}
<h2>
    Pagination_With_Data_Table_issue</h2>
    
<style type="text/css" title="currentStyle">
   @@import "http://datatables.net/release-datatables/media/css/demo_page.css";
   @@import "http://datatables.net/release-datatables/media/css/demo_table.css";
  </style>
<script type="text/javascript" language="javascript" src="http://datatables.net/release-datatables/media/js/jquery.js"></script>
<script type="text/javascript" language="javascript" src="http://datatables.net/release-datatables/media/js/jquery.dataTables.js"></script>
<script type="text/javascript" charset="utf-8">
    $(document).ready(function () {
        $('#example').dataTable({
            "bServerSide": true,
            "bProcessing": true,
            "sPaginationType": "full_numbers",
            "sAjaxSource": '@Url.Action("Pagination_With_Data_Table_issue_getData")'
        });
    });
</script>
<div id="dynamic">
<table cellpadding="0" cellspacing="0" border="0" class="display" id="example">
 <thead>
  <tr>
   <th width="20%">Rendering engine</th>
   <th width="25%">Browser</th>
   <th width="25%">Platform(s)</th>
   <th width="15%">Engine version</th>
   <th width="15%">CSS grade</th>
  </tr>
 </thead>
 <tbody>
 </tbody>
 <tfoot>
  <tr>
   <th>Rendering engine</th>
   <th>Browser</th>
   <th>Platform(s)</th>
   <th>Engine version</th>
   <th>CSS grade</th>
  </tr>
 </tfoot>
</table>
</div>
While initialization of the table plugin, we are using bServerSide and bProcessing to true, sPaginationType to full_number and finally sAjaxSource to controller action.

Controller action-
        public ActionResult Pagination_With_Data_Table_issue()
        {
            return View();
        }

        public ActionResult Pagination_With_Data_Table_issue_getData(TableParameter param)
        {
            var data = new[]{   
                new []{"Trident test","Internet Explorer 4.0","Win 95+","4","X"},
             new []{"Trident","Internet Explorer 5.0","Win 95+","5","C"},
             new []{"Trident","Internet Explorer 5.5","Win 95+","5.5","A"},
             new []{"Trident","Internet Explorer 6","Win 98+","6","A"},
             new []{"Trident","Internet Explorer 7","Win XP SP2+","7","A"},
             new []{"Trident","AOL browser (AOL desktop)","Win XP","6","A"},
             new []{"Gecko","Firefox 1.0","Win 98+ / OSX.2+","1.7","A"},
             new []{"Gecko","Firefox 1.5","Win 98+ / OSX.2+","1.8","A"},
             new []{"Gecko","Firefox 2.0","Win 98+ / OSX.2+","1.8","A"},
             .
                .
                .
                .
                .
            };

            var pagedData = data.Skip(param.iDisplayStart).Take(param.iDisplayLength);

            return Json(new
            {
                sEcho = param.sEcho,
                iTotalRecords = data.Count(),
                iTotalDisplayRecords = data.Count(),
                aaData = pagedData
            }, JsonRequestBehavior.AllowGet);
        }
In this case we are using the input parameter for filtering the correct data. Finally the return JSON matches the format explained in the second case. The array of data we have prepared form the following link-

http://datatables.net/examples/examples_support/json_source.txt

This explains everything. Let me know for any query. You can download the code here.

Thursday, May 24, 2012

Show/hide detail in a table using jQuery and MVC 3

This is another simple example where we will be showing some record in a table and there will be some plus/ minus image in each row and on click of the image we will be showing some detail of the record. And we will toggle the images and data. To do that lets have the following view models-
namespace MVCRazor.ViewModel
{
    public class TableRowItemViewlModel
    {
        public int Id { get; set; }
        public string Name { get; set; }
        public string Email { get; set; }
        public TableRowItemDetailViewlModel Detail { get; set; }
    }
    public class TableRowItemDetailViewlModel
    {
        public string Address { get; set; }
        public string Sex { get; set; }
        public string Nationality { get; set; }
    }
}
The model is simple and self explanatory. And we are going to use the following view to display the tabular data and the controller to read the data. In the sample we have taken some in memory object for data access-
namespace MVCRazor.Controllers
{
    public class TableRowDetailController : Controller
    {
        List<TableRowItemViewlModel> data = new List<TableRowItemViewlModel>();
        public TableRowDetailController()
        {
            data.AddRange(new List<TableRowItemViewlModel>(){
            new TableRowItemViewlModel(){ Id =1,Name="Name 1", Email ="Email 1", Detail=new TableRowItemDetailViewlModel(){Address="Address 1", Nationality="Nationality 1", Sex="Sex 1"}},
            new TableRowItemViewlModel(){ Id =2,Name="Name 2", Email ="Email 2", Detail=new TableRowItemDetailViewlModel(){Address="Address 2", Nationality="Nationality 2", Sex="Sex 2"}},
            new TableRowItemViewlModel(){ Id =3,Name="Name 3", Email ="Email 3", Detail=new TableRowItemDetailViewlModel(){Address="Address 3", Nationality="Nationality 3", Sex="Sex 3"}},
            new TableRowItemViewlModel(){ Id =4,Name="Name 4", Email ="Email 4", Detail=new TableRowItemDetailViewlModel(){Address="Address 4", Nationality="Nationality 4", Sex="Sex 4"}},
            new TableRowItemViewlModel(){ Id =5,Name="Name 5", Email ="Email 5", Detail=new TableRowItemDetailViewlModel(){Address="Address 5", Nationality="Nationality 5", Sex="Sex 5"}},
            new TableRowItemViewlModel(){ Id =6,Name="Name 6", Email ="Email 6", Detail=new TableRowItemDetailViewlModel(){Address="Address 6", Nationality="Nationality 6", Sex="Sex 6"}},
            new TableRowItemViewlModel(){ Id =7,Name="Name 7", Email ="Email 7", Detail=new TableRowItemDetailViewlModel(){Address="Address 7", Nationality="Nationality 7", Sex="Sex 7"}},
            new TableRowItemViewlModel(){ Id =8,Name="Name 8", Email ="Email 8", Detail=new TableRowItemDetailViewlModel(){Address="Address 8", Nationality="Nationality 8", Sex="Sex 8"}},
            new TableRowItemViewlModel(){ Id =9,Name="Name 9", Email ="Email 9", Detail=new TableRowItemDetailViewlModel(){Address="Address 9", Nationality="Nationality 9", Sex="Sex 9"}},
        });
        }

        public ActionResult Index()
        {
            return View((from c in data
                         select new TableRowItemViewlModel() { Id = c.Id, Name = c.Name, Email = c.Email }).ToList());
        }
    }
}
@model List<MVCRazor.ViewModel.TableRowItemViewlModel>
@{
    ViewBag.Title = "Index";
    Layout = "~/Views/Shared/_Layout.cshtml";
}
<h2>Index</h2>
<style>
.tbl {border:1px solid gray; }
.tbl td{padding:5px 10px 5px 10px; }
.tbl th{padding:5px 10px 5px 10px;background-color:Gray;color:White }
.pm{ cursor:pointer;}
.plus
{
    background:url('http://www.quimicasuiza.com/images/extras/plus-minus.gif') 0 -16px;
    display:block;
    width:16px;
    height:16px;
}
.minus
{
    background:url('http://www.quimicasuiza.com/images/extras/plus-minus.gif') 0 0;
    display:block;
    width:16px;
    height:16px;
}
.detail
{
    background-color:#d4d0d8;    
    padding:7px;
}
</style>
<table class="tbl" cellpadding="0" cellspacing="0">
<tr><th>&nbsp;</th><th>Id</th><th>Name</th><th>Email</th></tr>
@foreach (var row in Model)
{ 
    <tr><td><span class="pm plus"></span></td><td>@row.Id</td><td>@row.Name</td><td>@row.Email</td></tr>
}
</table>
The above controller and the view will display the data like below-
We are going to use the following script to retrieve data from the controller and show hide the details.
<script type="text/javascript">
    var colCount;
    $(document).ready(function () {
        colCount = $(".tbl tr:first").children().length;
        $("tr:odd").css("background-color", "#f0f3f4");
        $(".pm").click(function () {
            if ($(this).hasClass("plus")) {
                $(this).removeClass("plus").addClass("minus");
                if (!$(this).closest("tr").next().hasClass("detail")) {
                    getDetail($(this).closest("tr"));
                }
                else
                    $(this).closest("tr").next().show();
            }
            else {
                if ($(this).closest("tr").next().hasClass("detail"))
                    $(this).closest("tr").next().hide();
                $(this).removeClass("minus").addClass("plus");
            }
        });
    });
    function getDetail(row) {
        var rowNew = $("<tr class='detail'><td colspan=" + colCount + "></td></tr>");
        $.ajax({
            type: "get",
            timeout: 30000,
            data: "id=" + row.find("td:eq(1)").html(),
            url: '@Url.Action("GetDetail")',
            dataType: "json",
            contentType: "application/json; charset=utf-8",
            success: function (result) {
                rowNew.find("td").append("<b>Address </b>: " + result.Address);
                rowNew.find("td").append("<br /><b>Sex </b>: " + result.Sex);
                rowNew.find("td").append("<br /><b>Nationality </b>: " + result.Nationality);
                row.after(rowNew);
            },
            error: function (a, b, c) {
                debugger;
            }
        });
    }
</script>
In this we are showing plus/minus button as span with CSS class pm. On click of the span we are checking whether it has a class named plus . Based on that in line 8 and 18 we are toggling the classes plus/minus.

If the line has class called plus, in the line 9 we are checking whether the next row of the container row has a CSS class called detail. Suppose it has that class then we are simply showing that row(in line 13). Otherwise we are calling a function called getDetail in line 10 by passing the current row. In that function we are building a row in memory with same columnspan as of the table row. Then we are passing the id of row and doing a ajax call to the controller to get the data. In the success of the ajax call we are adding the newly created row next to the current row(in line 37).

On click of span, if the condition check in the line 7 does not have a class named plus, that means the detail is already loaded and open. We are simply hiding the detail in line(16-17).

The controller method for getting detail is as follows-
        public JsonResult GetDetail(int id)
        {
            return Json((from c in data
                         where c.Id == id
                         select c.Detail).First(), JsonRequestBehavior.AllowGet);
        }
In the image we can see things in action. If we click the button multiple time, the ajax call will happen one time only. And on subsequent click it just show and hide the data.

Monday, May 14, 2012

Conditional if in attribute in a HTML element using razor syntax.

This is little interesting. While on asp.net forum, I came across a requirement of conditional if in deciding css class of a HTML tag. I thought of writing this as a blog post.

Lets take a small section of the following code-
@for (int i = 0; i < 10; i++)
{
    if (i%2 == 0)
    {
    <div class="a">
        Test
    </div>
    }
    else
    {
    <div class="b">
        Test
    </div>
    }
}
 
In the above code segment we are simply checking the odd and even and setting the css class as "a" or "b". But the code is not optimal. We can reduce the lines of code by the following-
@for (int i = 0; i < 10; i++)
{
    <div class="@(i % 2 == 0? 'a': 'b')">
        Test
    </div>
}

Wednesday, May 2, 2012

jQuery datepicker problem with control generated in loop in asp.net MVC

Today I have faced a unique problem with datepicker while working in asp.net MVC.

I have added some textboxes using HTML.TextBoxFor inside a loop and then implemented datepicker on the textboxes. Part of the code goes like this-
<script src="http://ajax.aspnetcdn.com/ajax/jQuery/jquery-1.7.js" type="text/javascript"></script>
<script src="http://ajax.aspnetcdn.com/ajax/jquery.ui/1.8.9/jquery-ui.js" type="text/javascript"></script>
<link href="http://ajax.aspnetcdn.com/ajax/jquery.ui/1.8.9/themes/redmond/jquery-ui.css" rel="stylesheet" type="text/css" />
<script type="text/javascript">
    $(document).ready(function () {
        $("input[id*=DateTaken]").datepicker({
            dateFormat: "dd/mm/yy",
            changeMonth: true,
            changeYear: true
        });
    });
</script>

@for (int i = 0; i < 10; i++)
{
    @Html.TextBoxFor(m=> m.EventDate)
}
Now problem is that datepicker is enabled in all the textboxes, but on selection of date from the picker its adding the selected date to the first text box only. On digging further I can see the textboxes HTML got generated like below-
<input id="DateTaken" name="EventDate" type="text" value="" />
<input id="DateTaken" name="EventDate" type="text" value="" />
<input id="DateTaken" name="EventDate" type="text" value="" />
.
.
.
That is control got generated with same id and name 10 times. This is not a valid HTML. But suppose we need the control to be generated like this. Such control collection will be posted as an array with the name EventDate to the controller.

This can be solved very easily. Just generating different ID for each input control. That is the following code change will solve the problem-
@Html.TextBoxFor(m=> m.EventDate, new { @id = "DateTaken"+item.ToString() })

Friday, March 2, 2012

Binding, posting to a Dictionary in MVC 3 using jQuery ajax

This is a continuation of the previous two posts-
  1. Posting an array or generic list of string to asp.net MVC 3 using jQuery ajax
  2. Posting and binding generic list or array of complex object in MVC 3 using jQuery ajax
In this post we are going to discuss how to post data to a Dictionary using jQuery ajax. Lets have a simple model from the previous post and pass value to the action method as dictionary of the model we get the following controller method-
[HttpPost]
public ActionResult Binding_posting_to_a_dictionary_using_ajax(Dictionary<string, UserModel> userList)
{
    return PartialView("Success");
}
To work with dictionary the default model binder will accept the data in a particular format. If we consider key of the first element of the dictionary as firstkey then we have to give the name of the input parameter as [0].value.ModelPropertyName. So, for the first item we can give the names like-
<input name="[0].key" value="firstkey" type="hidden">
<input name="[0].value.FirstName" value="" type="text">
<input name="[0].value.LastName" value="" type="text">
<input name="[0].value.Age" value="" type="text">
If we see the above code block, we can see there is a hidden field for maintaining the key of the dictionary element and the value of the hidden filed is nothing but the key of the dictionary element.

Below is the code for posting to a dictionary from jQuery ajax-
<div class="data">
    <h4>
        First User</h4>
    <input type="hidden" name="[0].key" value="first" />
    First Name: @Html.TextBox("[0].value.FirstName")
    Last Name: @Html.TextBox("[0].value.LastName")
    Age: @Html.TextBox("[0].value.Age")
</div>
<div class="data">
    <h4>
        Second User</h4>
    <input type="hidden" name="[1].key" value="second" />
    First Name: @Html.TextBox("[1].value.FirstName")
    Last Name: @Html.TextBox("[1].value.LastName")
    Age: @Html.TextBox("[1].value.Age")
</div>
<div class="data">
    <h4>
        Third User</h4>
    <input type="hidden" name="[2].key" value="third" />
    First Name: @Html.TextBox("[2].value.FirstName")
    Last Name: @Html.TextBox("[2].value.LastName")
    Age: @Html.TextBox("[2].value.Age")
</div>
<input type="button" id="submitData" value="Submit data" />
<script type="text/javascript">
    $(document).ready(function () {
        $("#submitData").click(function () {
            var datatopost = new Object();
            $(".data").each(function (i, item) {
                datatopost[$(item).find("input[name*=FirstName]").attr("name")] = $(item).find("input[name*=FirstName]").val();
                datatopost[$(item).find("input[name*=LastName]").attr("name")] = $(item).find("input[name*=LastName]").val();
                datatopost[$(item).find("input[name*=Age]").attr("name")] = $(item).find("input[name*=Age]").val();
                datatopost[$(item).find("input[name*=key]").attr("name")] = $(item).find("input[name*=key]").val();
            });
            $.ajax({
                url: '@Url.Action("Binding_posting_to_a_dictionary_using_ajax")',
                type: 'POST',
                traditional: true,
                data: datatopost,
                dataType: "json",
                success: function (response) {
                    alert(response);
                },
                error: function (xhr) {
                    alert(xhr);

                }
            });
        });
    });
</script>
[HttpPost]
       [HttpPost]
        public JsonResult Binding_posting_to_a_dictionary_using_ajax(Dictionary<string, UserModel> userList)
        {
            return Json("Success");
        }
Explanation of the jQuery code is given in the previous post. We can check the input data of the ajax call and the posted value of dictionary data in the image below-

Thursday, March 1, 2012

Posting and binding generic list or array of complex object in MVC 3 using jQuery ajax

This post is an extension of the previous post. Please go through the previous post before proceeding with this. In this post we are going to discuss about posting a generic list or array of complex object from jQuery ajax.

Before proceeding with the solution, lets see how the posting of list works in case of a normal form post. To start with lets have the following model, view and controller actions-
    public class UserModel
    {
        public int UserId { get; set; }
        public string FirstName { get; set; }
        public string LastName { get; set; }
        public int Age { get; set; }
    }
@model List<razor.Models.UserModel>
           
@using (Html.BeginForm())
{
    for (int i = 0; i < Model.Count; i++)
    {
        <div class="data">
        <h4>User ID: @Model[i].UserId</h4>
        First Name: @Html.TextBoxFor(m => m[i].FirstName)
        Last Name: @Html.TextBoxFor(m => m[i].LastName)
        Age: @Html.TextBoxFor(m => m[i].Age)
        <br /><br />
        </div> 
    }
    <input type="submit" value="Submit data" />
}

I think the above model and view are self explanatory.
        public ActionResult Binding_posting_to_generic_collection_of_custom_type_using_ajax()
        {
            List<UserModel> users = new List<UserModel>();
            for (int i = 0; i < 5; i++)
            {
                users.Add(new UserModel() {UserId=i, FirstName = "FirstName " + i.ToString(), LastName = "LastName " + i.ToString(), Age = i +34});
            }
            return PartialView(users);
        }
        [HttpPost]
        public ActionResult Binding_posting_to_generic_collection_of_custom_type_using_ajax(List<UserModel> userList)
        {
            return PartialView("Success");
        }
In case of controller action, the first action is used to create some in-memory user object and render the view. The second action method is used to accept the posted data from the view.

Now if we study the generated HTML by the view engine, we can see the pattern of HTML generation for the name attribute of the text boxes. Each property of a user object in the list got the name as [index].PropertyName. As we are binding to a collection, the default model binder will search for the values for the properties of the User class that are prefixed by an index. That's why the view engine is generating the name attribute of that fashion.

So, to pass the data using jQuery ajax we need to pass the querystring parameter of that fashion for model binder. So, first thing that can come to mind we will use traditional:true in the ajax call like in the previous post and ajax() method will internally use param() to build the querystring format for us. But as I have studied, jquery 1.7 version does not support for getting querystring format for array of complex object. That is if we execute the following code-
unescape($.param(
 [{FirstName:"FN 1", LastName:"LN 1", Age:35},
 {FirstName:"FN 2", LastName:"LN 2", Age:36},
 {FirstName:"FN 3", LastName:"LN 3", Age:37}]
 ))
we get the following result-
undefined=undefined&undefined=undefined&undefined=undefined
So, what we can do is write a little jQuery code and also use traditional:true of the ajax call to achieve this. The final jQuery code for doing this as below-
@model List<razor.Models.UserModel>
@for (int i = 0; i < Model.Count; i++)
{
    <div class="data">
        <h4>
            User ID: @Model[i].UserId</h4>
        First Name: @Html.TextBoxFor(m => m[i].FirstName)
        Last Name: @Html.TextBoxFor(m => m[i].LastName)
        Age: @Html.TextBoxFor(m => m[i].Age)
    </div> 
}
<input type="button" id="submitData" value="Submit data" />
<script type="text/javascript">
    $(document).ready(function () {
        $("#submitData").click(function () {
            var datatopost=new Object();
            $(".data").each(function (i, item) {
                datatopost["[" + i + "].FirstName"] = $(item).find("input[name*=FirstName]").val();
                datatopost["[" + i + "].LastName"] = $(item).find("input[name*=LastName]").val();
                datatopost["[" + i + "].Age"] = $(item).find("input[name*=Age]").val();
            });
            $.ajax({
                url: '@Url.Action("Binding_posting_to_generic_collection_of_custom_type_using_ajax")',
                type: 'POST',
                traditional: true,
                data: datatopost,
                dataType: "json",
                success: function (response) {
                    alert(response);
                },
                error: function (xhr) {
                    alert(xhr);
                }
            });
        });
    });
</script>
What we are doing here is looping through all the data and manually building a JavaScript object datatopost with properties like-
"[index].FirstName"
"[index].LastName"
"[index].Age"
So the actual assignment will be something like-
datatopost["[0].FirstName"]="First Name 0"
datatopost["[0].LastName"]="Last Name 0"
datatopost["[0].Age"]="35"

datatopost["[1].FirstName"]="First Name 1"
datatopost["[1].LastName"]="Last Name 1"
datatopost["[1].Age"]="36"

and so on...
Now we have our JavaScript object datatopost is ready, which is a plain JavaScript object with some properties. And now we can use traditional:true to automate the query string format.

Now we will be able to successfully post data from jQuery ajax. We can also see the data posted during the ajax request in the image below-


Note:
We can also change the logic of creation of datatopost like below-
$(".data").each(function (i, item) {
   datatopost[$(item).find("input[name*=FirstName]").attr("name")] = $(item).find("input[name*=FirstName]").val();
   datatopost[$(item).find("input[name*=LastName]").attr("name")] = $(item).find("input[name*=LastName]").val();
   datatopost[$(item).find("input[name*=Age]").attr("name")] = $(item).find("input[name*=Age]").val();
});

Wednesday, February 29, 2012

Posting list of text box values to array or list using MVC 3

Lets describe the problem with example. Lets have the following model and view-
    public class SampleDataModel
    {
        public string Data1 { get; set; }
        public string Data2 { get; set; }
        public string Data3 { get; set; }
        public string Data4 { get; set; }
        public string Data5 { get; set; }
        public string Data6 { get; set; }
    }
@model razor.Models.SampleDataModel

@using (Html.BeginForm())
{
    @Html.TextBoxFor(x => x.Data1) <br />   
    @Html.TextBoxFor(x => x.Data2)<br />
    @Html.TextBoxFor(x => x.Data3)<br />
    @Html.TextBoxFor(x => x.Data4)<br />
    @Html.TextBoxFor(x => x.Data5)<br />
    @Html.TextBoxFor(x => x.Data6)<br />
    <input type="submit" value="Submit data" />
}
Now if we have a controller action method like-
        [HttpPost]
        public ActionResult Posting_list_of_text_to_array_or_list(razor.Models.SampleDataModel data)
        {
            return PartialView("Success");
        }
Then data will get posted properly. Mow suppose in some case we need to post the data to a string array(string[]) or to generic list(List<string>), then how we can do that using the same view.

Its very simple. Lets first check the generated HTML for the view.
<form method="post" action=/BlogPost/Posting_list_of_text_to_array_or_list?X-Requested-With=XMLHttpRequest>
<input id="Data1" type="text" name="Data1"><br>
<input id="Data2" type="text" name="Data2"><br>
<input id="Data3" type="text" name="Data3"><br>
<input id="Data4" type="text" name="Data4"><br>
<input id="Data5" type="text" name="Data5"><br>
<input id="Data6" type="text" name="Data6"><br>
<input value="Submit data" type="submit">
</form>
If we see the HTML, the name of the input box is same as the id of the input box. There is one beauty of the default model binder in MVC 3 that if it finds some form fields with the same name then it try to convert it collection or array. So, we can achieve by changing the name of the input box to the parameter name of the controller action like below-
@model razor.Models.SampleDataModel

<script type="text/javascript">
    $(document).ready(function () {
        $(".similar").attr("name", "data");
    });
</script>

@using (Html.BeginForm())
{
    @Html.TextBoxFor(x => x.Data1, new { @class = "similar" }) <br />   
    @Html.TextBoxFor(x => x.Data2, new { @class = "similar" })<br />
    @Html.TextBoxFor(x => x.Data3, new { @class = "similar" })<br />
    @Html.TextBoxFor(x => x.Data4, new { @class = "similar" })<br />
    @Html.TextBoxFor(x => x.Data5, new { @class = "similar" })<br />
    @Html.TextBoxFor(x => x.Data6, new { @class = "similar" })<br />
    <input type="submit" value="Submit data" />
}
What is done here is simple. Added a CSS class to the text boxes and using jQuery we have set the name attribute of the text boxes to a same value. Now if we add a action method like-
        [HttpPost]
        public ActionResult Posting_list_of_text_to_array_or_list(List data)
        {
            return PartialView("Success");
        }
or
        [HttpPost]
        public ActionResult Posting_list_of_text_to_array_or_list(string[] data)
        {
            return PartialView("Success");
        }
The values of the text boxes will get posted without any issue.

Posting an array or generic list of string to asp.net MVC 3 using jQuery ajax

This is a simple post that we will be using to post an array of value type or a generic list of value. We will be using string[] and List for our example. Lets have a vary basic controller action method that will be used for this purpose
        [HttpPost]
        public JsonResult Binding_posting_to_Array_or_List(string[] data)
        {
            return Json("success");
        }
Or
        [HttpPost]
        public JsonResult Binding_posting_to_Array_or_List(List data)
        {
            return Json("success");
        }
Now lets have a sample jQuery code to call the controller method as below-
 <script type="text/javascript">
    $(document).ready(function () {
        $("#btn").click(function () {
            $.ajax({
                url: '@Url.Action("Binding_posting_to_Array_or_List")',
                type: 'POST',
                data: { data: ["value 1", "value 2", "value 3"] },
                dataType: "json",
                success: function (response) {
                    alert(response);
                },
                error: function (xhr) {
                    debugger;
                    alert(xhr);

                }
            });
        });
    });
</script>
<input type="button" id="btn" value="Save data" />
But if we check the posted value at runtime in controller, we will find null value got posted-


The reason is MVC expects the data in querystring pattern. And we are passing data as a JSON object. The code will work if we pass data as querystring-
data: 'data=value 1&data=value 2&data=value 3',
Now jQuery ajax has a built in feature to solve this problem. That is the use of traditional option in the ajax call. If we pass the data as JSON object and set the option traditional:true,, jQuery will internally convert input data in querystring format. jQuery ajax method does this by using jQuery.param() API method. So, the final working sample of ajax call is as below-
 <script type="text/javascript">
     $(document).ready(function () {
        $("#btn").click(function () {
            $.ajax({
                url: '@Url.Action("Binding_posting_to_Array_or_List")',
                type: 'POST',
                traditional:true,
                data: {data:["value 1", "value 2", "value 3"]},
                dataType: "json",
                success: function (response) {
                    alert(response);
                },
                error: function (xhr) {
                    debugger;
                    alert(xhr);

                }
            });
        });
    }); 
</script>
Following image shows how the value gets converted to querystring format after using traditional option in the ajax call. This image is taken during run time using Firefox.