Thursday, April 19, 2012

Teleik MVC Grid Ajax edit and drop down binding

Are you using telerik grid control in your MVC3 application and you need to bind dropdown on edit dynamically based on the row selection, here is the example for you which displays a grid with customers and their states and on editing a customer we bring data of states based on customer id and show them in a drop down in the grid.

Controller: ~/Controller/HomeController.cs

public class HomeController
{

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

     [GridAction]
     public ActionResult _GetCustomers()
        {
            // do your stuff here to get customer's data
            return View(
                new GridModel<testModel1>{
                    Data = db.GetCustomers()
                }
                );
        }


[GridAction]
        [HttpPost]
        public ActionResult _UpdateCustomer(testModel1 objTest)
        {
            // update the customer
            return View(
                new GridModel<testModel1>
                {
                    Data = db.GetCustomers()
                }
                );
        }

       public JsonResult GetStatesOnCustomer(int CustId)
        {
            var states = new SelectList(GetStates(CustId), "St_Id", "St_name");
            return Json( states , JsonRequestBehavior.AllowGet);
        }

}


Model class:

public class testModel1
    {
        public int CustId { get; set; }
        public int StateId { get; set; }
       // This is the key for grid to find out the name of display and editor templates
        [UIHint("State"), Required]
        public string State { get; set; }
    }

public class States
{
       public int St_Id { get; set; }
       public string St_name { get; set; }
}


Telerik grid  ~/Views/Customers.cshtml



function onSave(e) {
        var selected = $(e.form).find('# ddState ').val();
        if (selected == 0) {
            alert("Please select a state");
            return false;
        }
    }

    function onEdit(e) {
       //Get the customer id from the row selected
        var custId = parseInt(e.dataItem['CustId']);
       //get the dom instance of state drop down
        statedd = $(e.form).find('#ddState').data('tDropDownList');
       // make a ajax call to the controller with customer id as parameter to fetch states dynamically based on   customer id
        $.ajax({
            type: "GET",
            async: false,
            cache: false,
            url: '@Url.Action(" GetStatesOnCustomer ", "Home")',
            dataType: 'json',
            data: { CustId:  custId  },
            success: function (states) {
                var prop;
                var propCount = 0;
                for (prop in  states )
                    propCount++;

                if (propCount > 0) {
                    //bind the returned value to the state drop down
                     states .splice(0, 0, { Selected: false, Text: '--Select--', Value: 0 });
                     statedd  .dataBind(suppliers);
                     statedd  .reload();
                     statedd  .select(function (dataItem) {
                        return dataItem.Value == e.dataItem['StateId'];
                    });
                }
                else {
                    $('a[class="t-button t-grid-cancel"]').click();
                    alert("States not found");
                }
            },
            error: function () {
                alert('Failed to retrieve states.');
            }
        });
    }



@(Html.Telerik().Grid<testModel1>()
.Name("testGrid")
.DataKeys(keys =>
{
keys.Add(o => o.CustId);
})
.DataBinding(dataBinding =>
{
dataBinding.Ajax()
.Select("_GetCustomers", "Home")
.Update("_UpdateCustomer", "Home");
})
.Columns(columns =>
{
columns.Bound(o => o.CustId).Width(100);
columns.Bound(o => o.State).Width(230);
columns.Command(commands => commands.Edit()).Title("Edit").Width(200);
})
.ClientEvents(events=>events.OnSave("onSave").OnEdit("onEdit"))
.Pageable()
)

Display Template: ~/Views/DisplayTemplates/State.cshtml

@model testModel1
@Model.State

Editor Template:  ~/Views/EditorTemplates/ State.cshtml

@using Telerik.Web.Mvc.UI
@(Html.Telerik().DropDownList() .Name("ddState").HtmlAttributes(new { width="100"}) )


Things to remember:
1)Create display and editor templates in the folder structure as specified in bold
2)UIHint must be defined in the Model(as we did for State in testModel1.cs)
3)Finally specify all the telerik references that are required for the Grid(You can find it here)

Feel free to comment..

1 comment: