如何使用 Kendo MVVM 和 c# 从服务器端 API 调用发出 Kendo 数据源请求?
How to make Kendo Datasource request from server side API call using Kendo MVVM and c#?
我正在使用 HTML 页面作为前端,我必须将一行 json 数据传输到数据库,我应该如何将一整行值作为参数传输到服务器端功能或从服务器端请求数据源来填充实体?
这是我的 html 代码:
<div id="example">
<div id="kendoGrid"
data-role="grid"
data-pageable=" true"
data-sortable=" true"
data-filterable="true"
data-toolbar="['create','save', 'cancel']"
data-editable="inline"
data-columns="[
{ 'field': 'Id', 'width': 100 },
{ 'field': 'ShortName', 'width': 100 },
{ 'field': 'FullName', 'width': 100 },
{ 'field': 'ContactPerson', 'width': 100 },
{ 'field': 'CurrentCurrencyCode', 'width': 100 },
{ 'field': 'Adress1', 'width': 100 },
{ 'field': 'CompanyCity', 'width': 100 },
{ 'field': 'CompanyState', 'width': 100 },
{ 'field': 'CompanyCountry', 'width': 100 },
{ 'field': 'ZipPostCode', 'width': 100 },
{ 'field': 'TelArea', 'width': 100 },
{ command: ['edit', 'update'], title: 'Actions', width: '250px' },
]"
data-bind="source: products"
style=" height :500px"></div>
</div>
这是我成功完全填充网格的视图模型代码
document.onreadystatechange = function () {
var viewModel = kendo.observable({
products: new kendo.data.DataSource({
schema: {
//data:"Data",
total: "Count",
model: {
Id: "Id",
fields: {
Id: { type: "int" },
ShortName: { editable:true, type: "string" },
FullName: { editable: true, type: "string" },
ContactPerson: { editable: true, type: "string" },
CurrentCurrencyCode: { editable: true, type: "int" },
Adress1: { editable: true, type: "string" },
CompanyState: { editable: true, type: "string" },
CompanyCity: { editable: true, type: "string" },
CompanyCountry: { editable: true, type: "string" },
ZipPostCode: { editable: true, type: "string" },
TelArea: { editable: true, type: "string" }
}
}
},
batch: true,
transport: {
read: {
url: "/api/Companies/GetAllCompanies",
dataType: "json"
},
create: {
type: 'POST',
// data: { request: {defcompny} , type: "create" },
url: "/api/Companies/SaveDefCompny", // here you need correct api url
dataType: 'json'
//contentType:"json"
},
//update: {
// url: "/api/Companies/SaveDefCompny", // here you need correct api url
// dataType: "json"
//},
destroy: {
url: "/api/Companies/Delete", // here you need correct api url
dataType: "json"
},
parameterMap: function (data, operation) {
if (operation !== "read" && data) {
debugger;
//return kendo.stringify({ defcompny: data.models[0] });
return JSON.stringify({ product: data.models[0] });
//return {"defcompny": "mydata" };
}
}
}
})
});
// var gridData = viewModel.product;
kendo.bind(document.getElementById("example"), viewModel);
}
这是我使用的服务器端代码,当我发出调用请求或如何发出数据源请求来填充实体时,它的实体必须填充值?
[HttpPost]
//product must have the values on view model operation create call and sending product data but it is null
public string SaveDefCompny( DefCompanyDTO product)
{
//return defcompny.save();
RPDBEntities data = new RPDBEntities();
var def = new DefCompany();
{
def.Id = product.Id;
def.CurrentCurrencyCode = product.CurrentCurrencyCode;
def.ShortName = product.ShortName;
def.FullName = product.FullName;
def.ContactPerson = product.ContactPerson;
def.Address1 = product.Address1;
def.CompanyCity = product.CompanyCity;
def.CompanyState = product.CompanyState;
def.CompanyCountry = product.CompanyCountry;
def.ZipPostCode = product.ZipPostCode;
def.TelArea = product.TelArea;
}
data.DefCompanies.Add(def);
data.SaveChanges();
return def.ShortName;
//return Json(new[] { product }.ToDataSourceResult(request, ModelState));
}
参数产品有空值我已经使用参数字符串产品进行了测试,但 api 没有进行调用我尝试传递字符串值但仍然 api 无法调用?
我会使用 JQuery 或 AJAX 调用从 HTML 将其作为 JSON
字符串传递给服务器。
然后,在我的控制器中,我将使用 post 方法作为:
[HttpPost]
public string SaveDefCompny(string serializeddata)
{
DefCompanyDTO product = NewtonSoft.JsonConvert.DeSerializeObject(serializeddata);
}
我对 Telerik 在他们的演示中指定的场景使用 AJAX 绑定:
public ActionResult Products_Create([DataSourceRequest]DataSourceRequest request, ProductViewModel product)
{
if (ModelState.IsValid)
{
using (var northwind = new NorthwindEntities())
{
// Create a new Product entity and set its properties from the posted ProductViewModel
var entity = new Product
{
ProductName = product.ProductName,
UnitsInStock = product.UnitsInStock
};
// Add the entity
northwind.Products.Add(entity);
// Insert the entity in the database
northwind.SaveChanges();
// Get the ProductID generated by the database
product.ProductID = entity.ProductID;
}
}
// Return the inserted product. The grid needs the generated ProductID. Also return any validation errors.
return Json(new[] { product }.ToDataSourceResult(request, ModelState));
}
您可以在 Telerik demo 中了解更多信息。
由于您在评论中提到您的数据来自 WebAPI,因此 example 也可能对您有所帮助。
更新 (source):
如果您使用 Kendo 网格的 MVC 包装器,则不会发生这种情况。由于此 ASP.NET MVC 行为,网格被配置为发出 POST 请求。不过请确保您已包括 kendo.aspnetmvc.min.js。可以在 docs.
中找到更多信息
By default Kendo Grid for ASP.NET MVC should make POST requests when
configured for ajax binding. This is implemented by a custom
DataSource transport and schema. Those are defined in the
kendo.aspnetmvc.min.js. Make sure that this file is included after the
other Kendo JavaScript files. More info can be found in the
introduction help topic.
Solution: Correct Order Of JavaScript Files
<script src="/Scripts/kendo.web.min.js"></script> <-- or kendo.all.min.js -->
<script src="/Scripts/kendo.aspnetmvc.min.js"></script>
我正在使用 HTML 页面作为前端,我必须将一行 json 数据传输到数据库,我应该如何将一整行值作为参数传输到服务器端功能或从服务器端请求数据源来填充实体?
这是我的 html 代码:
<div id="example">
<div id="kendoGrid"
data-role="grid"
data-pageable=" true"
data-sortable=" true"
data-filterable="true"
data-toolbar="['create','save', 'cancel']"
data-editable="inline"
data-columns="[
{ 'field': 'Id', 'width': 100 },
{ 'field': 'ShortName', 'width': 100 },
{ 'field': 'FullName', 'width': 100 },
{ 'field': 'ContactPerson', 'width': 100 },
{ 'field': 'CurrentCurrencyCode', 'width': 100 },
{ 'field': 'Adress1', 'width': 100 },
{ 'field': 'CompanyCity', 'width': 100 },
{ 'field': 'CompanyState', 'width': 100 },
{ 'field': 'CompanyCountry', 'width': 100 },
{ 'field': 'ZipPostCode', 'width': 100 },
{ 'field': 'TelArea', 'width': 100 },
{ command: ['edit', 'update'], title: 'Actions', width: '250px' },
]"
data-bind="source: products"
style=" height :500px"></div>
</div>
这是我成功完全填充网格的视图模型代码
document.onreadystatechange = function () {
var viewModel = kendo.observable({
products: new kendo.data.DataSource({
schema: {
//data:"Data",
total: "Count",
model: {
Id: "Id",
fields: {
Id: { type: "int" },
ShortName: { editable:true, type: "string" },
FullName: { editable: true, type: "string" },
ContactPerson: { editable: true, type: "string" },
CurrentCurrencyCode: { editable: true, type: "int" },
Adress1: { editable: true, type: "string" },
CompanyState: { editable: true, type: "string" },
CompanyCity: { editable: true, type: "string" },
CompanyCountry: { editable: true, type: "string" },
ZipPostCode: { editable: true, type: "string" },
TelArea: { editable: true, type: "string" }
}
}
},
batch: true,
transport: {
read: {
url: "/api/Companies/GetAllCompanies",
dataType: "json"
},
create: {
type: 'POST',
// data: { request: {defcompny} , type: "create" },
url: "/api/Companies/SaveDefCompny", // here you need correct api url
dataType: 'json'
//contentType:"json"
},
//update: {
// url: "/api/Companies/SaveDefCompny", // here you need correct api url
// dataType: "json"
//},
destroy: {
url: "/api/Companies/Delete", // here you need correct api url
dataType: "json"
},
parameterMap: function (data, operation) {
if (operation !== "read" && data) {
debugger;
//return kendo.stringify({ defcompny: data.models[0] });
return JSON.stringify({ product: data.models[0] });
//return {"defcompny": "mydata" };
}
}
}
})
});
// var gridData = viewModel.product;
kendo.bind(document.getElementById("example"), viewModel);
}
这是我使用的服务器端代码,当我发出调用请求或如何发出数据源请求来填充实体时,它的实体必须填充值?
[HttpPost]
//product must have the values on view model operation create call and sending product data but it is null
public string SaveDefCompny( DefCompanyDTO product)
{
//return defcompny.save();
RPDBEntities data = new RPDBEntities();
var def = new DefCompany();
{
def.Id = product.Id;
def.CurrentCurrencyCode = product.CurrentCurrencyCode;
def.ShortName = product.ShortName;
def.FullName = product.FullName;
def.ContactPerson = product.ContactPerson;
def.Address1 = product.Address1;
def.CompanyCity = product.CompanyCity;
def.CompanyState = product.CompanyState;
def.CompanyCountry = product.CompanyCountry;
def.ZipPostCode = product.ZipPostCode;
def.TelArea = product.TelArea;
}
data.DefCompanies.Add(def);
data.SaveChanges();
return def.ShortName;
//return Json(new[] { product }.ToDataSourceResult(request, ModelState));
}
参数产品有空值我已经使用参数字符串产品进行了测试,但 api 没有进行调用我尝试传递字符串值但仍然 api 无法调用?
我会使用 JQuery 或 AJAX 调用从 HTML 将其作为 JSON
字符串传递给服务器。
然后,在我的控制器中,我将使用 post 方法作为:
[HttpPost]
public string SaveDefCompny(string serializeddata)
{
DefCompanyDTO product = NewtonSoft.JsonConvert.DeSerializeObject(serializeddata);
}
我对 Telerik 在他们的演示中指定的场景使用 AJAX 绑定:
public ActionResult Products_Create([DataSourceRequest]DataSourceRequest request, ProductViewModel product)
{
if (ModelState.IsValid)
{
using (var northwind = new NorthwindEntities())
{
// Create a new Product entity and set its properties from the posted ProductViewModel
var entity = new Product
{
ProductName = product.ProductName,
UnitsInStock = product.UnitsInStock
};
// Add the entity
northwind.Products.Add(entity);
// Insert the entity in the database
northwind.SaveChanges();
// Get the ProductID generated by the database
product.ProductID = entity.ProductID;
}
}
// Return the inserted product. The grid needs the generated ProductID. Also return any validation errors.
return Json(new[] { product }.ToDataSourceResult(request, ModelState));
}
您可以在 Telerik demo 中了解更多信息。
由于您在评论中提到您的数据来自 WebAPI,因此 example 也可能对您有所帮助。
更新 (source):
如果您使用 Kendo 网格的 MVC 包装器,则不会发生这种情况。由于此 ASP.NET MVC 行为,网格被配置为发出 POST 请求。不过请确保您已包括 kendo.aspnetmvc.min.js。可以在 docs.
中找到更多信息By default Kendo Grid for ASP.NET MVC should make POST requests when configured for ajax binding. This is implemented by a custom DataSource transport and schema. Those are defined in the kendo.aspnetmvc.min.js. Make sure that this file is included after the other Kendo JavaScript files. More info can be found in the introduction help topic.
Solution: Correct Order Of JavaScript Files
<script src="/Scripts/kendo.web.min.js"></script> <-- or kendo.all.min.js --> <script src="/Scripts/kendo.aspnetmvc.min.js"></script>