Friday, 31 July 2015

JSON Call in MVC


Controller Function :

public ActionResult getdata(){
    var model = new{value= "Bar"}
    return Json(model, JsonRequestBehavior.AllowGet);
}

View Script

$.ajax({
    type : "GET",
    dataType : "json",
    url : "@Url.action("getdata","Home")",
    success: function(data) {
        alert(data.value);
//Enter code here 
    }
});




Mask Input Of Telerik MVC


Mask Input Of Telerik MVC 

@(Html.Kendo().MaskedTextBoxFor(model => model.Fax)
                                          .Name("Fax") //The name of the maskedtextbox is mandatory. It specifies the "id" attribute of the widget.
                                          .Mask("(000)000-0000") //Set mask value of the maskedtextbox
                                          .Value(Model.Phone) //Set value of the maskedtextbox
                                    )

Model Declaration  

[DisplayName("Fax"), AllowHtml]
        public string Fax { get; set; } 

Cancel delete data from telerik grid in MVC if any error occurs .

Cancel delete data from telerik grid in MVC if any error occurs .
   var grid = jQuery("#Grid").data("kendoGrid");
                // cancel changes
                grid.cancelChanges();

controler 
 [AcceptVerbs(HttpVerbs.Post)]
        public ActionResult EditingPopup_Destroy([DataSourceRequest] DataSourceRequest request, IssueCategoryModel model)
        {
         
                ModelState.AddModelError("Information", ex.Message);
                return Json(new[] { model }.ToDataSourceResult(request, ModelState));
         

        }

<script type="text/javascript">
    function onRequestEnd(e) {
              if (e.type === "update") {
         
            var grid = jQuery("#Grid").data("kendoGrid");
            grid.dataSource.read();
        }
        if (e.type === "create") {
                      var value = e.response.Errors;
            if (e.response.Errors) {

            } else {
           
                var grid = jQuery("#Grid").data("kendoGrid");
                grid.dataSource.read();
            }

        }
        if (e.type === "destroy") {
       
            if (e.response.Errors) {
                var grid = jQuery("#Grid").data("kendoGrid");
                // cancel changes
                grid.cancelChanges();
            } else {
                e.sender.read();
            }
        }

    }
   
</script>

Reload a Telerik Grid in MVC (Kendo MVC)

you can write down this code any function of that grid 

 var grid = jQuery("#Grid").data("kendoGrid");

                grid.dataSource.read();


example:

<script type="text/javascript">
    function onRequestEnd(e) {
              if (e.type === "update") {
         
            var grid = jQuery("#Grid").data("kendoGrid");
            grid.dataSource.read();
        }
        if (e.type === "create") {
                      var value = e.response.Errors;
            if (e.response.Errors) {

            } else {
           
                var grid = jQuery("#Grid").data("kendoGrid");
                grid.dataSource.read();
            }

        }
        if (e.type === "destroy") {
       
            if (e.response.Errors) {
                var grid = jQuery("#Grid").data("kendoGrid");
                // cancel changes
                grid.cancelChanges();
            } else {
                e.sender.read();
            }
        }

    }
   
</script>

Custom Grid inline editing with dropdownlist bound

View 

@model IEnumerable<PurchaseModel>

@(Html.Kendo().Grid<PurchaseModel>(Model)
    .Name("grid")
    .Columns(columns =>
        {
            columns.Bound(x => x.flagPartId).Hidden();
            columns.Bound(p => p.PartCode).Title("Part<font color='red'>*</font>").ClientTemplate("#if (PartCode == null) {# #=''# #} else {# #=PartCode# #}#").Width(150);
            columns.Bound(p => p.PartName).Title("Part Name<font color='red'>*</font>").ClientTemplate("#if (PartName == null) {# #=''# #} else {# #=PartName# #}#").Width(150);
            columns.Bound(p => p.PartCategoryID).Title("Part Category").Width(130).Filterable(ftb => ftb.Extra(false).Cell(cell => cell.Operator("contains")));
            columns.Bound(p => p.Quantity).Title("Quantity<font color='red'>*</font>").Width(90).Filterable(ftb => ftb.Extra(false).Cell(cell => cell.Operator("contains")));
            columns.Bound(p => p.Cost).Title("Cost per Unit<font color='red'>*</font>").Width(100).Filterable(ftb => ftb.Extra(false).Cell(cell => cell.Operator("contains")));
            columns.ForeignKey(p => p.Condition, (System.Collections.IEnumerable)ViewData["ddlCondition"], "Value", "Value").Title("Condition <font color='red'>*</font>").Width(100).Filterable(ftb => ftb.Extra(false).Cell(cell => cell.Operator("contains")));
            columns.Bound(p => p.PartSerialNo).Title("Serial Number").Width(120).Filterable(ftb => ftb.Extra(false).Cell(cell => cell.Operator("contains")));
            columns.Bound(itm => itm.WStatus).Hidden(true);
            columns.Template(@<text></text>).ClientTemplate(@"<input name='name#=renderNumberYes()#' type='radio' value='1' #= WStatus=='true' ? checked='checked':'' # />Yes
                            <input name='name#=renderNumberNo()#' type='radio' value='0' #= WStatus=='false' ? checked='checked':'' # />No
                            ").HeaderTemplate("Warranty Provided").Width(150);
            columns.Bound(p => p.Warranty).Title("Warranty Period").Width(150).Filterable(ftb => ftb.Extra(false).Cell(cell => cell.Operator("contains")));
            columns.ForeignKey(p => p.WarrantyType, (System.Collections.IEnumerable)ViewData["ddlUnit"], "Value", "Text").Title("Units").Width(90).Filterable(ftb => ftb.Extra(false).Cell(cell => cell.Operator("contains")));
            columns.Command(command => command.Destroy()).Width(90);
        })
        .ToolBar(toolBar =>
          {
              toolBar.Create();
              toolBar.Save();
          })
          .Editable(editable => editable.Mode(GridEditMode.InCell))
          .Events(even => even.Save("onSavePart").Edit("edit"))
          .Pageable(pager => pager.PageSizes(new int[] { 10, 20, 50 }))
          .Navigatable()
          .Scrollable(s => s.Height("auto"))
          .DataSource(dataSource => dataSource
          .Ajax()
          .ServerOperation(false)
          .Events(events => events.Error("error_handler").RequestEnd("onRequestEnd"))
          .Model(model =>
          {
              model.Id(p => p.PartDetailID);
              model.Field(p => p.PartCode);
              model.Field(p => p.WarrantyStatus).Editable(false);
              model.Field(p => p.Condition).DefaultValue("NEW");
              model.Field(p => p.Warranty);
              model.Field(p => p.WarrantyType).DefaultValue("Day(s)");
          })
         .PageSize(10)
         .Read(read => read.Action("EditingCustom_Read", "Purchase"))
         .Create(create => create.Action("EditingCustom_Create", "Purchase"))
         .Update(update => update.Action("EditingCustom_Update", "Purchase"))
         .Destroy(destroy => destroy.Action("EditingCustom_Destroy", "Purchase"))
         .Batch(true)
         )
    )


2 editor template
@model string

@(Html.Kendo().DropDownListFor(m => m)
.Name("PartCode")
        .AutoBind(false)
        .Filter("startswith")
        .MinLength(1)
       // .Suggest(true)
        .DataTextField("PartCode")
        .DataValueField("PartCode")
        //.BindTo((System.Collections.IEnumerable)ViewData["ddlPart"])
        .DataSource(dataSource =>
        {
            dataSource.Read(read => read.Action("BindPartCode", "Purchase"))
                    .ServerFiltering(false);
        })
       
)
@Html.ValidationMessageFor(m => m)

===============================
@model string

@(Html.Kendo().DropDownListFor(m => m)
.Name("PartName")
        .AutoBind(false)
        .Filter("startswith")
        .MinLength(1)
       // .Suggest(true)
        .DataTextField("PartName")
        .DataValueField("PartName")
        //.BindTo((System.Collections.IEnumerable)ViewData["ddlPart"])
        .DataSource(dataSource =>
        {
            dataSource.Read(read => read.Action("BindPartCode", "Purchase"))
                    .ServerFiltering(false);
        })
        
)
@Html.ValidationMessageFor(m => m)

Model Value declaration 

        [DisplayName("Part Code")]
        [UIHint("PartCode")]
        public string PartCode { get; set; }

        [DisplayName("Part Name")]
        [UIHint("PartName")]
        public string PartName { get; set; }

Controller :
 public ActionResult EditingCustom_Read([DataSourceRequest] DataSourceRequest request)
        {

            return Json(model.ToDataSourceResult(request), JsonRequestBehavior.AllowGet);
        }
        [AcceptVerbs(HttpVerbs.Post)]
        public ActionResult EditingCustom_Update([DataSourceRequest] DataSourceRequest request,
            [Bind(Prefix = "models")]IEnumerable<PurchaseModel> model)
        {
           
            if (model != null && ModelState.IsValid)
            {
                foreach (var product in model)
                {
                       //write code
                }
            }
            return Json(TempPurchaseDynamicGrid.ToDataSourceResult(request, ModelState));
        }
        [AcceptVerbs(HttpVerbs.Post)]
        public ActionResult EditingCustom_Create([DataSourceRequest] DataSourceRequest request,
            [Bind(Prefix = "models")]IEnumerable<PurchaseModel> model)
        {
            var results = new List<PurchaseModel>();

            if (model != null && ModelState.IsValid)
            {
                  //write code
            }
           
            return Json(TempPurchaseDynamicGrid.ToDataSourceResult(request, ModelState));
        }
        [AcceptVerbs(HttpVerbs.Post)]
        public ActionResult EditingCustom_Destroy([DataSourceRequest] DataSourceRequest request,
            [Bind(Prefix = "models")]IEnumerable<PurchaseModel> model)
        {
            foreach (var product in model)
            {
               //write code
            }

            return Json(TempPurchaseDynamicGrid.ToDataSourceResult(request, ModelState));
        }





Thursday, 23 July 2015

Telerik MVC Batch editing


View 
@(Html.Kendo().Grid<Kendo.Mvc.Examples.Models.ProductViewModel>()    
    .Name("Grid")    
    .Columns(columns => {        
        columns.Bound(p => p.ProductName);
        columns.Bound(p => p.UnitPrice).Width(140);
        columns.Bound(p => p.UnitsInStock).Width(140);
        columns.Bound(p => p.Discontinued).Width(100);
        columns.Command(command => command.Destroy()).Width(110);
    })
    .ToolBar(toolbar => {
        toolbar.Create();
        toolbar.Save();        
    })
    .Editable(editable => editable.Mode(GridEditMode.InCell))
    .Pageable()
    .Navigatable()
    .Sortable()
    .Scrollable()
    .DataSource(dataSource => dataSource        
        .Ajax()         
        .Batch(true)
        .PageSize(20)
        .ServerOperation(false)                
        .Events(events => events.Error("error_handler"))
        .Model(model => model.Id(p => p.ProductID))
        .Create("Editing_Create", "Grid")
        .Read("Editing_Read", "Grid")
        .Update("Editing_Update", "Grid")
        .Destroy("Editing_Destroy", "Grid")
    )
)
<script type="text/javascript">
    function error_handler(e) {    
        if (e.errors) {
            var message = "Errors:\n";
            $.each(e.errors, function (key, value) {
                if ('errors' in value) {
                    $.each(value.errors, function() {
                        message += this + "\n";
                    });
                }
            });        
            alert(message);
        }
    }
</script>

Controller
 public ActionResult Editing_Read([DataSourceRequest] DataSourceRequest request)
        {
            return Json(productService.Read().ToDataSourceResult(request));
        }

        [AcceptVerbs(HttpVerbs.Post)]
        public ActionResult Editing_Create([DataSourceRequest] DataSourceRequest request, [Bind(Prefix = "models")]IEnumerable<ProductViewModel> products)
        {
            var results = new List<ProductViewModel>();

            if (products != null && ModelState.IsValid)
            {
                foreach (var product in products)
                {
                    productService.Create(product);
                    results.Add(product);
                }
            }

            return Json(results.ToDataSourceResult(request, ModelState));
        }

        [AcceptVerbs(HttpVerbs.Post)]
        public ActionResult Editing_Update([DataSourceRequest] DataSourceRequest request, [Bind(Prefix = "models")]IEnumerable<ProductViewModel> products)
        {
            if (products != null && ModelState.IsValid)
            {
                foreach (var product in products)
                {
                    productService.Update(product);
                }
            }

            return Json(products.ToDataSourceResult(request, ModelState));
        }

        [AcceptVerbs(HttpVerbs.Post)]
        public ActionResult Editing_Destroy([DataSourceRequest] DataSourceRequest request, [Bind(Prefix = "models")]IEnumerable<ProductViewModel> products)
        {            
            if (products.Any())
            {
                foreach (var product in products)
                {
                    productService.Destroy(product);
                }
            }

            return Json(products.ToDataSourceResult(request,ModelState));
        }