Quantcast
Channel: MVC – AuthorCode
Viewing all articles
Browse latest Browse all 10

Convert MVC WebGrid data into JSON string and use it in controller

$
0
0

In this article I will demonstrates how to generate the JSON string from the WebGrid data in your MVC web application. In addition, you will learn how easy it is to use this JSON data in your controller. I assume that you have some basic knowledge of the MVC framework so I am not describing that how to start the MVC project from the scratch.

This article will covers the following things

– Show the data in the WebGrid from the database
– Create the JSON string on the click of button.
– how to use the JSON string in the controller.

Bind WebGrid from the database

the following is the tbl_employee model:

namespace MvcApplication1
{
    using System;
    using System.Collections.Generic;
 
    public partial class tbl_Employee
    {
        public int employeeId { get; set; }
        public string empName { get; set; }
        public Nullable<int> age { get; set; }
        public Nullable<int> department_id { get; set; }
        public Nullable<decimal> salary { get; set; }
 
        public virtual tbl_EmployeeDetails tbl_EmployeeDetails { get; set; }
    }
}

Passing JSON data from view to controller
In the script block(in the Index View- see below), there is a JavaScript function named ‘gridTojson’ that will convert the data of the grid in to the JSON string. The jQuery click event of the btnSave send this JSON data as parameter by calling the controller’s action result named ‘UpdateGridData’.

View [Index.cshtml]

The following is the Index.cshtml view that contains the grid.

@model List<MvcApplication1.tbl_Employee>
@{
    ViewBag.Title = "Home Page";
}
@section featured {
    <section class="featured">
        <div class="content-wrapper">
            <hgroup class="title">
                <h1>@ViewBag.Title.</h1>
                <h2>@ViewBag.Message</h2>
            </hgroup>           
        </div>
    </section>
}
<div>
</div>
<link rel="stylesheet" href="http://code.jquery.com/ui/1.10.3/themes/smoothness/jquery-ui.css">
 <script src="http://code.jquery.com/ui/1.8.20/jquery-ui.min.js" ></script>
<table>
    <tr><td>
            <div id="EmployeeViewGrid">
            @{  
                var grid1 = new WebGrid(source: Model, canPage: true, ajaxUpdateContainerId: "gridContent");
        @grid1.GetHtml(mode: WebGridPagerModes.All, tableStyle: "webGrid",
            headerStyle: "header",
            alternatingRowStyle: "alt",
            selectedRowStyle: "select",
            rowStyle: "description",
            htmlAttributes: new { id = "employeeGrid" },
            fillEmptyRows: false,
            columns: grid1.Columns(
             grid1.Column("EmployeeId", header: "EmployeeId"),
             grid1.Column("EmpName", header: "EmpName"),
             grid1.Column("Age", header: "Age"),
             grid1.Column("Salary",format: (item) => Html.TextBox("Salary", (int)item.Salary, new { @class = "spinnertxt" }), header: "Salary")))
            }
            </div>  
        </td> </tr>
    <tr><td> <input type="button" value="Save All" id="btnsave" /> </td></tr>
</table>
<style>
    .spinnertxt{margin: 0;padding: 2px;font-size: 1em;}
</style>
 <script src="/Scripts/jquery-1.7.1.js"></script>
<script>
    $('#btnsave').click(function (e) {
        //debugger;
        var _griddata = gridTojson();
        var url = '@Url.Action("UpdateGridData")';
            $.ajax({
                url: url,
                type: 'POST',
                data: { griddata: _griddata }
            }).done(function (data) {
                if (data != "") {
                    $('#message').html(data);
                }
            });
     });
 
    function gridTojson() {
        var json = '{';
        var otArr = [];
        var tbl2 = $('#employeeGrid tbody tr').each(function (i) {
            if ($(this)[0].rowIndex != 0) {
                x = $(this).children();
                var itArr = [];
                x.each(function () {
                    if ($(this).children('input').length > 0) {
                        itArr.push('"' + $(this).children('input').val() + '"');
                    }
                    else {
                        itArr.push('"' + $(this).text() + '"');
                    }
                });
                otArr.push('"' + i + '": [' + itArr.join(',') + ']');
            }
        })
        json += otArr.join(",") + '}'
        return json;
    }
</script>

gridtoJson() function will return the following JSON string of the Grid’s data( as shown below)

{"0": ["1","David","30","25000"],"1": ["2","A. John","28","15000"],"2": ["3","Orato bens","35","28000"],"3": ["4","Ban G","50","50000"],"4": ["5","Alfredo","30","20000"],"5": ["6","Thakur","55","50"],"6": ["7","Ankur123","22","2100"],"7": ["8","rajusanju","55","10"],"8": ["9","22222","55","12"],"9": ["10","Thakur123","55","50"]}

You can see the above view on the browser shown as:

employee grid in mvc4

Controller

The controller is named HomeController and the first method is Index. This method return the view of Index page that contains the grid of employee data. And the second method below is UpdateGridData that will call on the click of the button ‘btnSave’.

    public class HomeController : Controller
    {
        private EmployeeDatabaseEntities _dbcontext = new EmployeeDatabaseEntities();
 
        public ActionResult Index()
        {
            ViewBag.Message = "Modify this template to jump-start your ASP.NET MVC application.";
 
            _dbcontext = new EmployeeDatabaseEntities();
           // var list = new _dbcontext.tbl_Employee>
            return View(_dbcontext.tbl_Employee.ToList<tbl_Employee>());
 
        }
        public ActionResult UpdateGridData( string gridData)
        {
            var log = Newtonsoft.Json.JsonConvert.DeserializeObject<Dictionary<string, string[]>>(gridData);
 
            return Json("Update Successfully");
        }
}

Viewing all articles
Browse latest Browse all 10

Trending Articles