How to display data from database into Kendo Grid - visual-studio

I want to display my data from database to kendo grid but the result is no display. I don't know what happen can you see correct my code if there's wrong syntax for display my data into kendo grid. I try so many solution but my problem is still the same and here is my Code in Controller
namespace TBSWebApp.Controllers
{
public class LoanApplicationController : Controller
{
// GET: LoanApplication
public ActionResult LoanApplication()
{
return View();
}
public static List<DisplayRecords> objCmp = new List<DisplayRecords>();
static LoanApplicationController()
{
string strServer = GlobalVariable.prServer;
string strDatabase = GlobalVariable.prDatabase;
string mainconn = string.Format(ConfigurationManager.ConnectionStrings["BackendEntities"].ConnectionString, strServer, strDatabase);
SqlConnection sqlconn = new SqlConnection(mainconn);
string s1 = "SELECT InvoiceNo,InvoiceDate,FileAs,LoanBalance FROM tblInvoice LEFT OUTER JOIN tblContacts ON tblInvoice.CustomerID = tblContacts.ContactID WHERE LEFT(InvoiceNo,2) ='LR'";
SqlCommand sqlcomm = new SqlCommand(s1);
sqlcomm.Connection = sqlconn;
sqlconn.Open();
SqlDataReader sdr = sqlcomm.ExecuteReader();
List<DisplayRecords> objmodel = new List<DisplayRecords>();
if (sdr.HasRows)
{
while (sdr.Read())
{
objCmp.Add(new DisplayRecords { InvoiceNo = sdr["InvoiceNo"].ToString(), InvoiceDate =Convert.ToDateTime(sdr["InvoiceDate"].ToString()), FileAs = sdr["FileAs"].ToString(), Amount = sdr["LoanBalance"].ToString() });
}
sqlconn.Close();
}
}
public ActionResult GetData([DataSourceRequest] DataSourceRequest dsRequest)
{
var result = objCmp.ToDataSourceResult(dsRequest);
return Json(result);
}
public ActionResult UpdateData([DataSourceRequest] DataSourceRequest dsRequest, DisplayRecords person)
{
if (person != null && ModelState.IsValid)
{
var toUpdate = objCmp.FirstOrDefault(p => p.InvoiceNo == person.InvoiceNo);
TryUpdateModel(toUpdate);
}
return Json(ModelState.ToDataSourceResult());
}
}
}
and this is my code in view LoanApplication.cshtml for my design in kendo grid
<div class="row">
<div style="width:100%;height:100%">
#(Html.Kendo().Grid<TBSWebApp.Models.DisplayRecords>().Name("LoanApplication")
.DataSource(dataSource => dataSource
.Ajax()
.Model(model => model.Id(m => m.InvoiceNo))
.Read(read => read.Action("GetData", "LoanApplication"))
.Update(up => up.Action("UpdatePerson", "LoanApplication"))
)
.Columns(columns =>
{
columns.Bound(c => c.InvoiceNo).Width(200);
columns.Bound(c => c.InvoiceDate);
columns.Bound(c => c.FileAs);
columns.Bound(c => c.Amount);
columns.Command(cmd => cmd.Edit());
})
.Pageable()
.Sortable()
.Editable(ed => ed.Mode(GridEditMode.PopUp).TemplateName("Person"))
)
</div>
and i don't think if there is wrong with my code in here . Can you enlighten me if I have something to config in some other settings, not just in controller and view and the below is the image of the result
and the below is my data from sql server:

Related

KendoUI (Telerik 2018) - TreeList is not showing newly created record till manual refresh

I am able to create new record in TreeList for MVC. But it shows newly created record only after refreshing the page. Edit and Delete works fine.
Razor Code
#(Html.Kendo().TreeList<KendoEx.Web.Models.Level>()
.Name("lvlTreeList")
.Toolbar(toolbar =>
{
toolbar.Create();
})
.Columns(columns =>
{
columns.Add().Field(e => e.LvlName).Title("Name").Width(120);
columns.Add().Field(e => e.LvlType).Title("Type").Width(80);
columns.Add().Field(e => e.Rating1).Title("Rating 1").Filterable(false).Width(100);
columns.Add().Field(e => e.Rating2).Title("Rating 2").Filterable(false).Width(100);
columns.Add().Command(c =>
{
c.CreateChild().Text("Add child");
c.Edit();
c.Destroy();
}).Width(180);
})
.Editable(e => e.Mode("inline"))
.DataSource(dataSource => dataSource
.Read(read => read.Action("GetLevel", "Level"))
.Create(create => create.Action("Save", "Level"))
.Update(update => update.Action("Save", "Level"))
.Destroy(delete => delete.Action("Remove", "Level"))
.Model(m =>
{
m.Id(f => f.Id);
m.ParentId(f => f.ParentLvl).DefaultValue(0);
m.Expanded(true);
m.Field(f => f.LvlName);
m.Field(f => f.LvlType);
m.Field(f => f.Rating1);
m.Field(f => f.Rating1);
}))
.Height(550))
Controller Methods
public JsonResult GetLevel([DataSourceRequest] DataSourceRequest request)
{
var lvlList = LoadLevels().ToTreeDataSourceResult(request);
return Json(lvlList, JsonRequestBehavior.AllowGet);
}
private IEnumerable<Level> LoadLevels()
{
IEnumerable<Level> lvlList = Enumerable.Empty<Level>(); ;
using (var client = new HttpClient())
{
client.BaseAddress = new Uri(ConfigurationManager.AppSettings["WebApiExUrl"]);
var responseTask = client.GetAsync("getlevel");
responseTask.Wait();
var result = responseTask.Result;
if (result.IsSuccessStatusCode)
{
var readTask = result.Content.ReadAsAsync<FormattedResult<Level>>();
readTask.Wait();
if (string.IsNullOrEmpty(readTask.Result.Error))
{
IEnumerable<Level> tempList = readTask.Result.Data;
lvlList = tempList.Select(m => new Level
{
Id = m.Id,
LvlName = m.LvlName,
LvlType = m.LvlType,
ParentLvl = m.ParentLvl,
Rating1 = m.Rating1,
Rating2 = m.Rating2,
hasChildren = tempList.Where(s => s.ParentLvl == m.Id).Count() > 0
});
}
}
}
return lvlList;
}
public JsonResult Save([DataSourceRequest] DataSourceRequest request, Level level)
{
if (level != null && ModelState.IsValid)
{
try
{
using (var client = new HttpClient())
{
client.BaseAddress = new Uri(ConfigurationManager.AppSettings["KpiApiUrl"]);
var postTask = client.PostAsJsonAsync("savelevel", level);
postTask.Wait();
var result = postTask.Result;
if (result.IsSuccessStatusCode)
{
var readTask = result.Content.ReadAsStringAsync();
readTask.Wait();
}
}
}
catch (Exception ex)
{
ModelState.AddModelError(string.Empty, "Unexpected error");
}
}
return Json(new[] { level }.ToTreeDataSourceResult(request, ModelState));
}
Model
public class Level
{
public int Id { get; set; }
public string LvlName { get; set; }
public string LvlType { get; set; }
public int? ParentLvl { get; set; }
[RegularExpression(#"^(\d{1,2}(\.\d{0,2})?)?(<|<=|>|>=)(\d{1,3}(\.\d{0,2})?)$", ErrorMessage = "Invalid")]
public string Rating1 { get; set; }
[RegularExpression(#"^(\d{1,2}(\.\d{0,2})?)?(<|<=|>|>=)(\d{1,3}(\.\d{0,2})?)$")]
public string Rating2 { get; set; }
}
If the 'Save' method returns
return Json(LoadLevels().ToDataSourceResult(request, ModelState), JsonRequestBehavior.AllowGet);
instead of
return Json(new[] { level }.ToTreeDataSourceResult(request, ModelState));
the TreeList shows duplicate records
The 'Save' event of TreeList also behaves in the same way.
function onSave() {
$("#lvlTreeList").data("kendoTreeList").dataSource.read();
}
Version Info: Telerik 2018.1.221.545, MVC 5.2, .NET 4.6
Please advise on this. Thanks.
Demo Link: https://demos.telerik.com/aspnet-mvc/treelist/editing
Calling read() in Sync event of DataSource, refreshes the TreeList and displays newly created level.
Razor Code
#(Html.Kendo().TreeList<..>()
.Name("lvlTreeList")
/*..*/
.DataSource(dataSource => dataSource
.Events(e => e.Sync("lvlTreeList_Sync"))
/*...*/
))
Javascript
<script>
function lvlTreeList_Sync() {
this.read();
}
</script>
Refer: https://www.telerik.com/forums/refresh-after-upda

kendo grid data depending on another kendo grid results UI for Asp.Net MVC

I Have two Kendo Grids (UI for Asp.Net MVC) on my page. The first grid gets results from database using an action method of a controller which is bound at grid initialization(I guess). The second grid should get the results of a column from first grid and pass as parameters to second grid which should pass these to action method of another controller bound to second grid. I tried to use autobind(false) but has no use. Please suggest.
Please try with the below code snippet.
VIEW
#(Html.Kendo().Grid<MvcApplication1.Models.TestModel>()
.Name("Grid")
.Columns(columns =>
{
columns.Bound(e => e.ID);
columns.Bound(e => e.Name);
})
.DataSource(dataSource => dataSource
.Ajax()
.Read(read => read.Action("GetData", "Home"))
)
.Events(events => events.Change("onChange"))
.Selectable(selectable => selectable
.Mode(GridSelectionMode.Single))
)
#(Html.Kendo().Grid<MvcApplication1.Models.ChildModel>()
.Name("ChildGrid")
.Columns(columns =>
{
columns.Bound(e => e.ChildID);
columns.Bound(e => e.ChildName);
})
.DataSource(dataSource => dataSource
.Ajax()
.Read(read => read.Action("GetChildData", "Home").Data("GetData"))
)
)
<script>
var ID = 0;
var Name = "";
function onChange(arg) {
ID = this.dataItem(this.select()).ID;
Name = this.dataItem(this.select()).Name;
$('#ChildGrid').data('kendoGrid').dataSource.read();
$('#ChildGrid').data('kendoGrid').refresh();
}
function GetData() {
return {
ID: ID,
Name: Name
};
}
</script>
CONTROLLER
public ActionResult GetChildData([DataSourceRequest] DataSourceRequest request, int ID, string Name)
{
List<ChildModel> lst = new List<ChildModel>();
if (ID == 0)
{
return Json(lst.ToDataSourceResult(request));
}
string str = ":" + ID + "_" + Name;
lst.Add(new ChildModel() { ChildID = 1, ChildName = "Name1" + str });
lst.Add(new ChildModel() { ChildID = 2, ChildName = "Name2" + str });
lst.Add(new ChildModel() { ChildID = 3, ChildName = "Name3" + str });
return Json(lst.ToDataSourceResult(request));
}
public ActionResult GetData([DataSourceRequest] DataSourceRequest request)
{
List<TestModel> lst = new List<TestModel>();
lst.Add(new TestModel() { ID = 1, Name = "Name1", MyDate = DateTime.Now });
lst.Add(new TestModel() { ID = 2, Name = "Name2", MyDate = DateTime.Now });
lst.Add(new TestModel() { ID = 3, Name = "Name3", MyDate = DateTime.Now });
return Json(lst.ToDataSourceResult(request));
}
MODEL
namespace MvcApplication1.Models
{
public class TestModel
{
public int ID { get; set; }
public string Name { get; set; }
[DataType(DataType.DateTime)]
public DateTime? MyDate { get; set; }
}
public class ChildModel
{
public int ChildID { get; set; }
public string ChildName { get; set; }
}
}
Let me know if any concern.
I have done something like that in my project. I've searched a lot and I finally realize that the solution is creating master and detail grids, the first gird will be the master and the second which get information from the first is detail, in my example is have two grid, one for Sport Branch and the other is for Federation. Federation get information from Sport Branch.
The Sport Branch grid:
<div >
#(Html.Kendo().Grid<SportBranchViewModel>()
.Name("grid")
.Columns(columns =>
{
columns.Bound(p => p.SportBranchTitle).Title("Title").Width(120);
columns.Command(command => { command.Edit().Text("Edit").UpdateText("OK").CancelText("Cancel");
command.Destroy().Text("Delete");
})
.Width(172);
})
.ToolBar(toolbar => toolbar.Create().Text("Create"))
.Editable(editable =>
{
editable.Mode(GridEditMode.InLine);
editable.DisplayDeleteConfirmation("Are you sure you want to delete");
})
.Scrollable()
.Sortable(sortable => sortable.AllowUnsort(true))
.ClientDetailTemplateId("federationtemplate")
.DataSource(dataSource => dataSource
.Ajax()
.Events(events => events.Error("onError"))
.Model(model => model.Id(p => p.SportBranchID))
.Read(read => read.Action("SportBranch_Read", "BaseData"))
.Update(update => update.Action("SportBranch_Update", "BaseData"))
.Create(create => create.Action("SportBranch_Create", "BaseData"))
.Destroy(destroy => destroy.Action("DeleteSportBranch", "BaseData"))
)
.Events(events => events.DataBound("collapseGrid"))
.HtmlAttributes(new { style = "height:400px;" }))
</div>
the Federation grid:
<script id="federationtemplate" type="text/kendo-tmpl">
#(Html.Kendo().Grid<SportBranchFederationViewModel>()
.Name("grid_#=SportBranchID#")
.Columns(columns =>
{
columns.Bound(p => p.FederationName).Title("Title").Width(200);
columns.Command(command =>
{
command.Edit().Text("Edit").UpdateText("OK").CancelText("Cancel");
command.Destroy().Text("Delete");
})
;
})
.ToolBar(toolbar =>
{
toolbar.Create().Text("Create");
}
)
.Editable(editable =>
{
editable.Mode(GridEditMode.InLine);
editable.DisplayDeleteConfirmation("Are you sure you want to delete?");
})
.Scrollable()
.Sortable(sortable => sortable.AllowUnsort(true))
.Pageable()
.Events( e=> e.DataBound("onDataBoundFederation"))
.DataSource(dataSource => dataSource
.Ajax()
.Events(events => events.Error("onError"))
.Model(model => model.Id(p => p.FederationID))
.Read(read => read.Action("SportBranchFederation_Read", "BaseData", new { sportBranchID = "#=SportBranchID#" }))
.Create(create => create.Action("SportBranchFederation_Add", "BaseData", new { sportBranchID = "#=SportBranchID#" }))
.Update(update => update.Action("SportBranchFederation_Update", "BaseData", new { sportBranchID = "#=SportBranchID#" }))
.Destroy(destroy => destroy.Action("SportBranchFederation_Destroy", "BaseData", new { sportBranchID = "#=SportBranchID#" }))
.PageSize(7)
)
.HtmlAttributes(new { style = "height:250px;" })
.ToClientTemplate()
)
</script>
in the controller:
public ActionResult SportBranchFederation_Read(int sportBranchID , [DataSourceRequest] DataSourceRequest request)
{
var data = _bvaDataService.GetFederations(sportBranchID);
return Json(CreateSportBranchFederationsFromFederations(data.ToList()).ToDataSourceResult(request));
}
Here is the steps:
put the second grid in a script tag and specify an id for the script tag.
In the first grid use the ClientDetailTemplateId() and pass the id of script tag which enclose the second grid.
In the action of second grid which you want pass the value of a column of the first gird use the expression "#= [column's name of the first grid]#" (here is "#=SportBranchID#"). Note the "#= #" can use in grid to use a value of a field from the current grid or another. I send this field to my read action to get the corresponding result( look at my controller)
adding ToClientTemplate() to the second grid
read these samples too :
http://demos.telerik.com/kendo-ui/grid/detailtemplate ,
http://demos.telerik.com/aspnet-mvc/grid/detailtemplate

Kendo Grid dynamic columns and update the batch Values

I have dynamic column in Kendo Grid through dynamic datatable, Everything is fine,
the problem is that, Kendo grid doesn't update the batch changing values in controller. plz look following, kindly help me.
#model System.Data.DataTable
#(Html.Kendo().Grid<dynamic>()
.Name("GridfilterHandler")
.Columns(columns =>
{
foreach (System.Data.DataColumn column in Model.Columns)
{
var c = columns.Bound(column.ColumnName).EditorTemplateName("gridColumn");
if (column.ColumnName == "ShowCheck")
{
columns.Template(#<text></text>).ClientTemplate("<input type='checkbox' #= ShowCheck ? checked='checked':'' # class='chkbx' />")
.HeaderTemplate("<input type='checkbox' id='masterCheckBox' onclick='checkAll(this)'/>").Width(200);
}
}
columns.Command(cmd => cmd.Edit());
})
.Pageable()
.Sortable()
.ToolBar(toolbar =>
{
toolbar.Save();
})
.Editable(ed => ed.Mode(GridEditMode.InCell))
// .Events(events => events.SaveChanges("onSaveChanges"))
.Filterable()
.Groupable()
.DataSource(dataSource => dataSource
.Ajax()
.Model(model =>
{
foreach (System.Data.DataColumn column in Model.Columns)
{
model.Field(column.ColumnName, column.DataType);
}
})
.Model(model =>
{
var id = Model.PrimaryKey[0].ColumnName;
model.Id(id);
foreach (System.Data.DataColumn column in Model.Columns)
{
model.Field(column.ColumnName, column.DataType);
// var field = model.Field(column.ColumnName, column.DataType);
}
})
.Batch(true)
.Read(read => read.Action("readfilterHandlerGrid", "Customize", new { filterTitle = Request.QueryString["filterTitle"] }))
.Update(update => update.Action("updatefilterHandlerGrid", "Customize"))
)
)
public ActionResult updatefilterHandlerGrid([DataSourceRequest] DataSourceRequest request, IEnumerable<dynamic> items)
{...............
}
public ActionResult updatefilterHandlerGrid([DataSourceRequest] DataSourceRequest request, [Bind(Prefix = "models")] IEnumerable<DataTable> products)
{.......................
}
I have tried above update events, but i get null values.
public ActionResult Update([DataSourceRequest] DataSourceRequest request, FormCollection model)
{
foreach (var key in model.Keys)
{
//Build you update query here
}
Here the Solution

send data to server with data() in kendo ui Grid

how can I send data to server with data() in kendo ui Grid when i have an Ienumerable parameter
I can't send data for " IEnumerable selectedNodeGroupClass " in Read function
Grid in View
#(Html.Kendo().Grid<UserProtocol>()
.Name("UserProtocol")
.DataSource(dataSource => dataSource
.Ajax()
.PageSize(15)
.Model(model => model.Id(m => m.tblProtocolID))
.Destroy(destroy => destroy.Action(MVC.Protocol.ActionNames.GridRowDelete, MVC.Protocol.Name))
.Read(read => read.Action(MVC.Protocol.ActionNames.ReadProtocols, MVC.Protocol.Name).Data("additionalData"))
)
.Columns(columns =>
{
columns.Template(#<text></text>).ClientTemplate("#= renderNumber(tblProtocolID)#").Width(30).HeaderTemplate(#<text><input type="checkbox" id="SelectAllCheckBox" value="false" /></text>);
columns.Bound(m => m.dateFrom).Title("تاریخ شروع");
columns.Bound(m => m.dateTo).Title("تاریخ پایان");
columns.Bound(m => m.isActive).Title("وضعیت").ClientTemplate("# if (isActive) { #" + "فعال" + "# } else { #" + "غیر فعال" + "# } #");
columns.Bound(m => m.fName).Title("نام");
columns.Bound(m => m.lName).Title("نام خانوادگي");
columns.Bound(m => m.shomarShenasname).Title("شماره شناسنامه");
columns.Bound(m => m.nationalCode).Title("کد ملی");
columns.Bound(m => m.fatherName).Title("نام پدر");
columns.Bound(m => m.isMale).Title("جنسيت").ClientTemplate("# if (isMale == true) { #" + "مرد" + "# } else { #" + "زن" + "# } #");
columns.Bound(m => m.birthDate).Title("تاريخ تولد");
columns.Template(#<text></text>).Width(40)
.ClientTemplate(Html.ActionLink(" ", MVC.Protocol.ActionNames.UpdateProtocol, new { tblProtocolID = "#= tblProtocolID #" }, new { #class = "tablectrl_small bBlue tipS edit MyCustomAddBtn" }).ToHtmlString());
columns.Template(#<text></text>).ClientTemplate(#"<a href=""\#"" class=""k-button-icontext tablectrl_small bRed tipS Remove MyCustomAddBtn"" data-id='#= tblProtocolID #' />").Width(40);//k-grid-delete
})
.Sortable()
.Pageable(p => p.Messages(x =>
{
x.Display("تعداد {0} - {1} از {2}");
x.Empty("اطلاعاتی برای نمایش در دسترس نیست.");
x.First("صفحه اول");
x.Last("صفحه آخر");
x.Previous("صفحه قبل");
x.Next("صفحه بعد");
x.ItemsPerPage("مورد");
x.Of("از");
x.Page("صفحه");
}))
.Scrollable()
.Editable(editable => editable.DisplayDeleteConfirmation(false))
//.Events(ev => ev.DataBound("resetRowNumber"))
.HtmlAttributes(new { style = "Height:430px; border-width:0px" })
.ToolBar(toolbar => toolbar.Template("<input id=\"DeleteAll\" type=\"button\" value=\"حذف انتخاب شده ها\" class=\"k-button\" />"))
)
Read function in my controller
[HttpPost]
public virtual JsonResult ReadProtocols([DataSourceRequest] DataSourceRequest request, UserProtocol userProtocol = null, IEnumerable<Test> selectedNodeGroupClass = null)
{
}
Test class :
public class Test
{
public string ID { get; set; }
public bool IsSelect { get; set; }
}
and data() function in jquery is
function additionalData() {
////Define a class
function Test(id, isSelect) {
this.ID=id,
this.IsSelect=isSelect
}
var arr = new Array();
$('#sidebarmenu1 input:checkbox').each(function () {
var value;
var checked = false;
if ($(this).is(":checked")) {
checked = true;
}
value = $(this).parent().parent().parent().find("input:hidden").first().val();
var s = new Test(value, checked);
arr.push(s);
});
var strAr = JSON.stringify(arr);
debugger;
return {
selectedNodeGroupClass:arr,
dateFrom: $("#dateFrom").val(),
dateTo: $("#dateTo").val(),
nationalCode: $("#nationalCode").val(),
shomarShenasname: $("#shomarShenasname").val(),
fName: $("#fName").val(),
lName:$("#lName").val(),
};
}
The default MVC Model binder requeres special format in which the data form collection should be composed. The whole magic is discussed in this forum thread. You can get a generic function that handles that 'transforming' of the JavaScript array from this code library which shows how the multiselect collection of objects is send to the server.

grid kendo ui edit create delete

I have page mvc cshtml
it contains an begin beginform:
#using (Html.BeginForm("ValiderLeChangement", "FichePersonnel", FormMethod.Post , new { id = "FormValider" } ))
{
}
inside this form i have put grid kendo ui in this kendo grid i want to use
create add and delete like example in Kendo UI DEMO ( http://demos.kendoui.com/web/grid/editing-inline.html)
i ve probleme with the action of create or delete or edit don't fire on server
my code is :
#(Html.Kendo().Grid(Model.ListeContact)
.Name("Grid")
.Editable(editable => editable.Mode(GridEditMode.InLine))
.ToolBar(toolbar => toolbar.Create())
.Columns(columns =>
{
columns.Bound(p => p.Nom).Title("Nom").Width(20);
columns.Bound(p => p.Prenom).Title("Prenom").Width(20);
//columns.Bound(p => p.Lien.Libelle).Title("Lien").Width(20).ClientTemplate(????? );
columns.Bound(p => p.Lien.Libelle).Title("Lien").Width(20);
columns.Bound(p => p.Tel).Title("Telephone").Width(20);
columns.Command(command => { command.Edit(); }).Width(30);
columns.Command(command => { command.Destroy(); }).Width(30);
///////// columns.Bound(p => p.IdContact).ClientTemplate("#= Delete(data) #").Title("Supprimer").Width(5);
})
.Sortable()
.DataSource(dataSource => dataSource
.Ajax()
.Batch(true)
.ServerOperation(true)
.Events(events => events.Error("error_handler"))
.Read(Read => Read.Action("ListeContact_Read", "FichePersonnel"))
.Model(model => model.Id(p => p.IdContact))
.Create(create => create.Action("EditingInline_Create", "FichePersonnel"))
.Update(update => update.Action("EditingInline_Update", "FichePersonnel"))
.Destroy(delete => delete.Action("EditingInline_Destroy", "FichePersonnel"))
)
)
How have you implemented your controller action method? Does it handles the request and return properly? It should be something like this:
public ActionResult EditingInline_Create([DataSourceRequest] DataSourceRequest request, ProductViewModel product)
{
if (product != null && ModelState.IsValid)
{
SessionProductRepository.Insert(product);
}
return Json(new [] { product }.ToDataSourceResult(request, ModelState));
}
Note the first argument DataSourceRequest and teh return type Json. Maybe that's what you're missing. Also I noticed that you're indicating ServerOperation(true). As far as I understand, you should not need that if you are using AJAX Binding as you are.
EDIT:
And so for the controller code, something like this:
public partial class TextosController : EditorImageBrowserController
{
public ActionResult ReadTextos([DataSourceRequest]DataSourceRequest request)
{
CostSimulatorModel modelo = new CostSimulatorModel(new Uri(#"http://localhost:53212/CostSimulatorModelService.svc/"));
IQueryable<Texto> textos = modelo.Textos;
DataSourceResult resultado = textos.ToDataSourceResult(request);
ViewData["Textos"] = textos;
return Json(resultado, JsonRequestBehavior.AllowGet);
}
public ActionResult CreateTexto([DataSourceRequest]DataSourceRequest request, Texto texto)
{
if (ModelState.IsValid)
{
CostSimulatorModel modelo = new CostSimulatorModel(new Uri(#"http://localhost:53212/CostSimulatorModelService.svc/"));
// Create a new Product entity and set its properties from the posted ProductViewModel
Texto entity = new Texto
{
TextoID = texto.TextoID,
Titulo = texto.Titulo,
Corpo = texto.Corpo,
IsPrivado = texto.IsPrivado,
TipoTextoID = texto.TiposTexto != null ? texto.TiposTexto.TipoTextoID : texto.TipoTextoID,
TiposTexto = texto.TiposTexto
};
modelo.AddToTextos(entity);
// Insert the entity in the database
modelo.SaveChanges();
// Get the ProductID generated by the database
texto.TextoID = entity.TextoID;
return Json(new[] { entity }.ToDataSourceResult(request, ModelState));
}
// Return the inserted product. The grid needs the generated ProductID. Also return any validation errors.
return Json(new[] { texto }.ToDataSourceResult(request, ModelState));
}
public ActionResult UpdateTexto([DataSourceRequest]DataSourceRequest request, Texto texto)
{
if (ModelState.IsValid)
{
CostSimulatorModel modelo = new CostSimulatorModel(new Uri(#"http://localhost:53212/CostSimulatorModelService.svc/"));
// Create a new Product entity and set its properties from the posted ProductViewModel
var entity = new Texto
{
TextoID = texto.TextoID,
Titulo = texto.Titulo,
Corpo = texto.Corpo,
IsPrivado = texto.IsPrivado,
TipoTextoID = texto.TiposTexto != null ? texto.TiposTexto.TipoTextoID : texto.TipoTextoID,
TiposTexto = texto.TiposTexto
};
// Attach the entity
modelo.AttachTo("Textos", entity);
modelo.UpdateObject(entity);
// Update the entity in the database
modelo.SaveChanges();
return Json(new[] { entity }.ToDataSourceResult(request, ModelState));
}
// Return the updated product. Also return any validation errors.
return Json(new[] { texto }.ToDataSourceResult(request, ModelState));
}
public ActionResult DestroyTexto([DataSourceRequest]DataSourceRequest request, Texto texto)
{
if (ModelState.IsValid)
{
CostSimulatorModel modelo = new CostSimulatorModel(new Uri(#"http://localhost:53212/CostSimulatorModelService.svc/"));
// Create a new Product entity and set its properties from the posted ProductViewModel
var entity = new Texto
{
TextoID = texto.TextoID
};
// Attach the entity
modelo.AttachTo("Textos", entity);
// Delete the entity
modelo.DeleteObject(entity);
// Delete the entity in the database
modelo.SaveChanges();
return Json(new[] { entity }.ToDataSourceResult(request, ModelState));
}
// Return the removed product. Also return any validation errors.
return Json(new[] { texto }.ToDataSourceResult(request, ModelState));
}
}

Resources