Hi~
I tried to save Grid data in Json format and send it back to controller to combine new query result, then return
back to Grid together.
My controller could get Json result from javascript as string, but the controller return format require .ToDataSourceResult
However, when I return string.ToDataSourceResult, it shows error.
How could I fix this?
public ActionResult ChemicalTestResult_Read([DataSourceRequest] DataSourceRequest request, string param1, string displayedDataAsJSON){ try { if (param1 != null && param1 != "") { var TestId = param1.Split(',').Reverse().ToList(); return Json(db.LIMS_Chemical_TestResult.Where(o => param1.Contains(o.TestId) && (o.Result_1 == null || o.Result_2 == null || o.Result_3 == null) && (o.isPermitted == "不合格" || o.isPermitted == null)).ToDataSourceResult(request)); } else { return stringdisplayedDataAsJSON.ToDataSourceResult(request); } } catch (Exception ex) { logger.Error(ex, "ChemicalTestResultController"); return new JavaScriptResult { Script = "alert('" + ex.ToString() + "');" }; }}var displayedData = $("#grid").data().kendoGrid.dataSource.view()var displayedDataAsJSON = JSON.stringify(displayedData);5 Answers, 1 is accepted
I am not sure I understand the scenario very well. Would you mind sharing a bit more code snippets and the value of stringdisplayedDataAsJSON or ideally - a runnable sample project? That would allow us to investigate.
Regards,
Alexander Popov
Telerik by Progress
I solve that issue but I got a new one...
I tried to update my edit row, however, there's an error with the JSON DateTime format.
I have two datetime fields, and I used an action to modify their value and the data could be saved.
But kendo grid show an error alert that DateTime format is not valid.
function query() { var s = ""; var gridWidget = $('#grid').data("kendoGrid"); var displayedData = $("#grid").data().kendoGrid.dataSource.view(); var displayedDataAsJSON = JSON.parse(JSON.stringify(displayedData)); gridWidget.dataSource.data(s); s = BarCode.value; $.ajax({ type: 'Get', url: '/TestResult/ChemicalTestResult/ChemicalTestResult_Read', contentType: 'application/json; charset=utf-8', data: { s: s}, dataType: 'json', success:function(data){ var a = 0; for(i = 0; i< displayedDataAsJSON.length; i++){ if (data[0].TestId != null){ if(displayedDataAsJSON[i].TestId == data[0].TestId){ a = 1; } } } if (a == 0 || displayedDataAsJSON.length == 0) { var json = displayedDataAsJSON.concat(data); gridWidget.dataSource.data(json); } else { gridWidget.dataSource.data(displayedDataAsJSON); } }, error:function(xhr) { alert(xhr.responseText); } })}
01.@(Html.Kendo().Grid<Template.Areas.TestResult.Models.LIMS_Chemical_TestResult>()02..Name("grid")03..Columns(columns =>04.{05. columns.Bound(p => p.TestId).Width(120);06. columns.ForeignKey(p => p.TestNo, (System.Collections.IEnumerable)ViewData["TestDesc"], "TestNo", "TestDesc").Width(90);07. columns.ForeignKey(p => p.TagNo, (System.Collections.IEnumerable)ViewData["TagDesc"], "TagNo", "TagDesc").Width(150);08. columns.ForeignKey(p => p.Plant, (System.Collections.IEnumerable)ViewData["Plant"], "ItemValue", "ItemName").Width(70);09. columns.Group(group => group10. .Title("管制值").HeaderHtmlAttributes(new { @style = "text-align: center" })11. .Columns(info =>12. {13. info.Bound(p => p.LowerLimit).Width(75);14. info.Bound(p => p.Standard).Width(90);15. info.Bound(p => p.UpperLimit).Width(75);16. })17. );18. columns.Bound(p => p.PLC_Data).Width(80);19. columns.Group(group => group20. .Title("檢測值").HeaderHtmlAttributes(new { @style = "text-align: center" })21. .Columns(info =>22. {23. info.Bound(p => p.Result_1).Width(75);24. info.Bound(p => p.Result_2).Width(75);25. info.Bound(p => p.Result_3).Width(75);26. })27. );28. columns.Bound(p => p.isPermitted).Width(80);29. columns.Bound(p => p.Notification).Width(120);30. columns.Bound(p => p.Description).Width(120);31. columns.Bound(p => p.Inspector).Width(120);32. columns.Bound(p => p.TestTime).Width(180).ClientTemplate("#= kendo.toString(kendo.parseDate(TestTime), 'G')#");33. columns.Bound(p => p.CreateTime).Width(180).ClientTemplate("#= kendo.toString(new Date(parseInt(CreateTime.substr(6))),'yyyy/MM/dd HH:mm:ss')#");34. })35..ToolBar(toolbar =>36.{37. //toolbar.Create().Text("新增");38. //toolbar.Excel().Text("匯出Excel");39. toolbar.Save().SaveText("儲存").CancelText("取消");40. //toolbar.Save();41.})42..Editable(editable => editable.Mode(GridEditMode.InCell))43..Pageable(pager => pager.Input(true).Numeric(true).Info(true).PreviousNext(true).Refresh(true).PageSizes(true))44..Sortable(sortable => sortable.AllowUnsort(true).SortMode(GridSortMode.MultipleColumn))45.//.Selectable(selectable => selectable.Mode(GridSelectionMode.Single).Type(GridSelectionType.Cell))46..Scrollable()47..Navigatable()48..AutoBind(false)49..Reorderable(reorder => reorder.Columns(true))50..Resizable(resize => resize.Columns(true))51..Excel(excel => excel.FileName(ViewBag.Title + ".xlsx"))52..HtmlAttributes(new { style = "height:100%;width:100%" })53..Events(events => events.Edit("edit").Save("save").DataBound("dataBound"))54..DataSource(dataSource => dataSource55. .Ajax()56. .Batch(true)57. .ServerOperation(false)58. .PageSize(10)59. .Events(events => events.Error("error_handler").RequestEnd("onRequestEnd"))60. .Model(model =>61. {62. model.Id(p => p.TestId);63. })64. .Create(Create => Create.Action("ChemicalTestResult_Create", "ChemicalTestResult"))65. .Update(Update => Update.Action("ChemicalTestResult_Update", "ChemicalTestResult"))66. )67.)
01.using Kendo.Mvc.Extensions;02.using Kendo.Mvc.UI;03.using LIMS.Controllers;04.using Newtonsoft.Json;05.using System;06.using System.Collections.Generic;07.using System.Linq;08.using System.Web;09.using System.Web.Mvc;10.using System.Web.Script.Serialization;11.using System.Xml.Linq;12.using Template.Areas.TestResult.Models;13. 14.namespace Template.Areas.TestResult.Controllers15.{ 16. public class ChemicalTestResultController : BaseApiController17. {18. // GET: TestResult/ChemicalTest19. [Authorize]20. public ActionResult Index()21. {22. try23. {24. ItemList();25. return View();26. }27. catch (Exception ex)28. {29. logger.Error(ex, "ChemicalTestResultController");30. return new JavaScriptResult { Script = "alert('" + ex.ToString() + "');" };31. }32. }33. 34. [AcceptVerbs(HttpVerbs.Get)]35. public JsonResult ChemicalTestResult_Read(string s)36. {37. try38. {39. var a = db.LIMS_Chemical_TestResult.Where(o => s.Contains(o.TestId) && (o.Result_1 == null || o.Result_2 == null || o.Result_3 == null) && (o.isPermitted == "不合格" || o.isPermitted == null)).ToList(); 40. JavaScriptSerializer serializer = new JavaScriptSerializer();41. return Json(a, JsonRequestBehavior.AllowGet);42. }43. catch (Exception ex)44. {45. logger.Error(ex, "ChemicalTestResultController");46. throw;47. }48. }49. 50. [AcceptVerbs(HttpVerbs.Post)]51. public ActionResult ChemicalTestResult_Update([DataSourceRequest] DataSourceRequest request, [Bind(Prefix = "models")]IEnumerable<LIMS_Chemical_TestResult> o)52. {53. try54. {55. foreach (var a in o)56. {57. a.Inspector = User.Identity.Name;58. a.TestTime = DateTime.Now;59. db.Entry(a).State = System.Data.Entity.EntityState.Modified;60. var b = db.LIMS_Chemical_TestResult.Where(p => p.TestId == a.TestId).Select(p => p.CreateTime).ToList();61. a.CreateTime = b.ElementAt(0).ToUniversalTime();62. db.SaveChanges();63. logger.Trace("{0}修改一筆檢驗資料,檢驗編號:{1}。", User.Identity.Name, a.TestId);64. }65. 66. return Json(o.ToDataSourceResult(request, ModelState));67. }68. catch (Exception ex)69. {70. logger.Error(ex, "ChemicalTestResultController");71. return new JavaScriptResult { Script = "alert('" + ex.ToString() + "');" };72. }73. }74. }75.}Here is Json :
[{"TestId":"1612220001-01","TestNo":"Cl-","TestEqp":"APT","TagNo":"1/2/4AL","Plant":"CF1","Class":"SB","UpperLimit":12,"Standard":11,"LowerLimit":10,"PLC_Data":null,"Result_1":1,"Result_2":null,"Result_3":null,"isPermitted":"不合格","isQualified":false,"Description":null,"Notification":null,"Inspector":"N000157994","TestTime":"/Date(1482909163000)/","CreateTime":"/Date(1482319378000)/"}]
Here is Json :
[{"TestId":"1612220001-01","TestNo":"Cl-","TestEqp":"APT","TagNo":"1/2/4AL","Plant":"CF1","Class":"SB","UpperLimit":12,"Standard":11,"LowerLimit":10,"PLC_Data":null,"Result_1":1,"Result_2":null,"Result_3":null,"isPermitted":"不合格","isQualified":false,"Description":null,"Notification":null,"Inspector":"N000157994","TestTime":"/Date(1482909163000)/","CreateTime":"/Date(1482319378000)/"}]
I reviewed the provided code snippets and noticed that number and date columns get their value by parsing the incoming data. This should not be necessary with a properly configured setup, since the DataSource uses the Model's field types to do the parsing automatically. However, I've also noticed that the DataSource's data method is used, which expects already parsed data and any parameters passed to it will not go through the DataSource's schema and would not be automatically parsed. My advice is to either convert all fields to their actual data type prior to passing them to the data method, or avoid using that method altogether.
Regards,
Alexander Popov
Telerik by Progress