فعال سازی عملیات CRUD در Kendo UI Grid
نویسنده: وحید نصیری
تاریخ: ۱۳۹۳/۰۸/۲۱ ۸:۵
آدرس: www.dntips.ir
| مطالب | ۳۶۹۴ |
| نویسندگان | ۲۷۶ |
| گروههای مطالب | ۱۰۲۴ |
| نقشههای راه | ۱۱۹ |
| دورهها | ۱۴ |
| اشتراکها | ۱۷۹۱۴ |
var productsDataSource = new kendo.data.DataSource({
transport: {
read: {
url: "api/products",
dataType: "json",
contentType: 'application/json; charset=utf-8',
type: 'GET'
},
create: {
url: "api/products",
contentType: 'application/json; charset=utf-8',
type: "POST"
},
update: {
url: function (product) {
return "api/products/" + product.Id;
},
contentType: 'application/json; charset=utf-8',
type: "PUT"
},
destroy: {
url: function (product) {
return "api/products/" + product.Id;
},
contentType: 'application/json; charset=utf-8',
type: "DELETE"
},
//...
},
schema: {
//...
model: {
id: "Id", // define the model of the data source. Required for validation and property types.
fields: {
"Id": { type: "number", editable: false }, //تعیین نوع فیلد برای جستجوی پویا مهم است
"Name": { type: "string", validation: { required: true } },
"IsAvailable": { type: "boolean" },
"Price": { type: "number", validation: { required: true, min: 1 } },
"AddDate": { type: "date", validation: { required: true } }
}
}
},
batch: false, // enable batch editing - changes will be saved when the user clicks the "Save changes" button
//...
}); namespace KendoUI06.Controllers
{
public class ProductsController : ApiController
{
public HttpResponseMessage Post(Product product)
{
if (!ModelState.IsValid)
return Request.CreateResponse(HttpStatusCode.BadRequest);
var id = 1;
var lastItem = ProductDataSource.LatestProducts.LastOrDefault();
if (lastItem != null)
{
id = lastItem.Id + 1;
}
product.Id = id;
ProductDataSource.LatestProducts.Add(product);
var response = Request.CreateResponse(HttpStatusCode.Created, product);
response.Headers.Location = new Uri(Url.Link("DefaultApi", new { id = product.Id }));
// گرید آی دی جدید را به این صورت دریافت میکند
response.Content = new ObjectContent<DataSourceResult>(
new DataSourceResult { Data = new[] { product } }, new JsonMediaTypeFormatter());
return response;
}
}
} var productsDataSource = new kendo.data.DataSource({
//...
schema: {
data: "Data",
total: "Total",
}
//...
}); namespace KendoUI06.Controllers
{
public class ProductsController : ApiController
{
public DataSourceResult Get(HttpRequestMessage requestMessage)
{
var request = JsonConvert.DeserializeObject<DataSourceRequest>(
requestMessage.RequestUri.ParseQueryString().GetKey(0)
);
var list = ProductDataSource.LatestProducts;
return list.AsQueryable()
.ToDataSourceResult(request.Take, request.Skip, request.Sort, request.Filter);
}
}
} response.Content = new ObjectContent<DataSourceResult>(
new DataSourceResult { Data = new[] { product } }, new JsonMediaTypeFormatter()); namespace KendoUI06.Controllers
{
public class ProductsController : ApiController
{
public HttpResponseMessage Delete(int id)
{
var item = ProductDataSource.LatestProducts.FirstOrDefault(x => x.Id == id);
if (item == null)
return Request.CreateResponse(HttpStatusCode.NotFound);
ProductDataSource.LatestProducts.Remove(item);
return Request.CreateResponse(HttpStatusCode.OK, item);
}
[HttpPut] // Add it to fix this error: The requested resource does not support http method 'PUT'
public HttpResponseMessage Update(int id, Product product)
{
var item = ProductDataSource.LatestProducts
.Select(
(prod, index) =>
new
{
Item = prod,
Index = index
})
.FirstOrDefault(x => x.Item.Id == id);
if (item == null)
return Request.CreateResponse(HttpStatusCode.NotFound);
if (!ModelState.IsValid || id != product.Id)
return Request.CreateResponse(HttpStatusCode.BadRequest);
ProductDataSource.LatestProducts[item.Index] = product;
return Request.CreateResponse(HttpStatusCode.OK);
}
}
} $("#report-grid").kendoGrid({
//....
editable: {
confirmation: "آیا مایل به حذف ردیف انتخابی هستید؟",
destroy: true, // whether or not to delete item when button is clicked
mode: "popup", // options are "incell", "inline", and "popup"
//template: kendo.template($("#popupEditorTemplate").html()), // template to use for pop-up editing
update: true, // switch item to edit mode when clicked?
window: {
title: "مشخصات محصول" // Localization for Edit in the popup window
}
},
columns: [
//....
{
command: [
{ name: "edit", text: "ویرایش" },
{ name: "destroy", text: "حذف" }
],
title: " ", width: "160px"
}
],
toolbar: [
{ name: "create", text: "افزودن ردیف جدید" },
{ name: "save", text: "ذخیرهی تمامی تغییرات" },
{ name: "cancel", text: "لغو کلیهی تغییرات" },
{ template: kendo.template($("#toolbarTemplate").html()) }
],
messages: {
editable: {
cancelDelete: "لغو",
confirmation: "آیا مایل به حذف این رکورد هستید؟",
confirmDelete: "حذف"
},
commands: {
create: "افزودن ردیف جدید",
cancel: "لغو کلیهی تغییرات",
save: "ذخیرهی تمامی تغییرات",
destroy: "حذف",
edit: "ویرایش",
update: "ثبت",
canceledit: "لغو"
}
}
}); using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Mvc;
using Kendo.DynamicLinq;
using KendoUI06Mvc.Models;
using Newtonsoft.Json;
namespace KendoUI06Mvc.Controllers
{
public class HomeController : Controller
{
public ActionResult Index()
{
return View(); // shows the page.
}
[HttpDelete]
public ActionResult DeleteProduct(int id)
{
var item = ProductDataSource.LatestProducts.FirstOrDefault(x => x.Id == id);
if (item == null)
return new HttpNotFoundResult();
ProductDataSource.LatestProducts.Remove(item);
return Json(item);
}
[HttpGet]
public ActionResult GetProducts()
{
var request = JsonConvert.DeserializeObject<DataSourceRequest>(
this.Request.Url.ParseQueryString().GetKey(0)
);
var list = ProductDataSource.LatestProducts;
return Json(list.AsQueryable()
.ToDataSourceResult(request.Take, request.Skip, request.Sort, request.Filter),
JsonRequestBehavior.AllowGet);
}
[HttpPost]
public ActionResult PostProduct(Product product)
{
if (!ModelState.IsValid)
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
var id = 1;
var lastItem = ProductDataSource.LatestProducts.LastOrDefault();
if (lastItem != null)
{
id = lastItem.Id + 1;
}
product.Id = id;
ProductDataSource.LatestProducts.Add(product);
// گرید آی دی جدید را به این صورت دریافت میکند
return Json(new DataSourceResult { Data = new[] { product } });
}
[HttpPut] // Add it to fix this error: The requested resource does not support http method 'PUT'
public ActionResult UpdateProduct(int id, Product product)
{
var item = ProductDataSource.LatestProducts
.Select(
(prod, index) =>
new
{
Item = prod,
Index = index
})
.FirstOrDefault(x => x.Item.Id == id);
if (item == null)
return new HttpNotFoundResult();
if (!ModelState.IsValid || id != product.Id)
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
ProductDataSource.LatestProducts[item.Index] = product;
//Return HttpStatusCode.OK
return new HttpStatusCodeResult(HttpStatusCode.OK);
}
}
} var productsDataSource = new kendo.data.DataSource({
transport: {
read: {
url: "@Url.Action("GetProducts","Home")",
dataType: "json",
contentType: 'application/json; charset=utf-8',
type: 'GET'
},
create: {
url: "@Url.Action("PostProduct","Home")",
contentType: 'application/json; charset=utf-8',
type: "POST"
},
update: {
url: function (product) {
return "@Url.Action("UpdateProduct","Home")/" + product.Id;
},
contentType: 'application/json; charset=utf-8',
type: "PUT"
},
destroy: {
url: function (product) {
return "@Url.Action("DeleteProduct","Home")/" + product.Id;
},
contentType: 'application/json; charset=utf-8',
type: "DELETE"
},
parameterMap: function (options) {
return kendo.stringify(options);
}
}, [HttpPost]
public ActionResult Update(IEnumerable<Product> products)
{
// ....
//Return emtpy result
return Json("");
} toolbar: [
{ name: "create", text: "افزودن ردیف جدید" },
{ name: "save", text: "ذخیرهی تمامی تغییرات" },
{ name: "cancel", text: "لغو کلیهی تغییرات" },
{ template: kendo.template($("#toolbarTemplate").html()) }
], <h2> <i>Invalid JSON primitive: Id.</i> </h2></span> [ArgumentException: Invalid JSON primitive: Id.] System.Web.Script.Serialization.JavaScriptObjectDeserializer.DeserializePrimitiveObject() +585
من وقتی این صفحه داره Get میشه با استفاده از تکه کد زیر خروجی بر میگردونم. مشکل نداره؟
string json = new JavaScriptSerializer().Serialize(list); return json;
$("#grid").kendoGrid({
// ...
columns:
[
{
field: "Your Field",
title: "Your Field Name",
width: "20%",
editor: function (container, options) {
$('<textarea cols="20" rows="4" data-bind="value: ' + options.field + '"></textarea>').appendTo(container);
}
},
// ...
]
// ...
}); columns: [
{ field: "units", title: "Units" },
{ field: "price", title: "Price" },
{ field: null, title: "Extended Price", template: '#= units * price #' }
] #=calculateField(data)#
//Passed data contains current row model
function calculateField(data) {
return data.f1 + " " + data.f2;
}
return Json(resultData.AsQueryable().ToDataSourceResult(dataSourceRequest, ModelState));
var dataSource = new kendo.data.DataSource({
// ...
error: function (e) {
window.SalesHub.OrderDetails_Error(e);
},
// ...
}); window.SalesHub.OrderDetails_Error = function(args) {
if (args.errors) {
var grid = $("#orderDetailsGrid").data("kendoGrid");
var validationTemplate = kendo.template($("#orderDetailsValidationMessageTemplate").html());
grid.one("dataBinding", function(e) {
e.preventDefault();
$.each(args.errors, function(propertyName) {
var renderedTemplate = validationTemplate({ field: propertyName, messages: this.errors });
grid.editable.element.find(".errors").append(renderedTemplate);
});
});
}
}; <script type="text/x-kendo-template" id="orderDetailsValidationMessageTemplate">
# if (messages.length) { #
<li>#=field#
<ul>
# for (var i = 0; i < messages.length; ++i) { #
<li>#= messages[i] #</li>
# } #
</ul>
</li>
# } #
</script> <DownloadNuGetExe Condition=" '$(DownloadNuGetExe)' == '' ">true</DownloadNuGetExe>
dataSource : {
// ....
requestStart: function () {
kendo.ui.progress($("#grid"), true);
},
requestEnd : function () {
kendo.ui.progress($("#grid"), false);
}
},
دیتای زیر را در نظر بگیرید:
[
{
OrderId: 1,
OrderName: 'order 1'
OrderItems: [
{
ProductId: 1,
ProductName: "sample name"
},
{
ProductId: 2,
ProductName: "sample name 2"
}
},
{
OrderId: 2,
OrderName: 'order 2'
OrderItems: [
{
ProductId: 55,
ProductName: "sample name 55"
},
{
ProductId: 18,
ProductName: "sample name18"
}
}
] من چطور میتونم مدلی تعریف کنم که بتوان مدل های nested این مدل رو پوشش بده:
var model = kendo.data.Model.define({
id: "OrderId",
fields: {
OrderId: {
type: "number",
editable: false
},
OrderName: {
type: "string",
editable: false
},
OrderItems: {
??????????????
}
}
}); آیا امکان تعریف مدلی به این شکل وجود دارد که بتوان در حین عملیات CRUD مدل های nested را هم تغییر داد؟
public class ProductsRequest
{
// نام این خاصیت نباید تغییر یابد
public IEnumerable<Product> Models { get; set; }
} public HttpResponseMessage Update(ProductsRequest products)
{
اینم کدهای بنده داخل View متناظر:
destroy: {
url: function (blog) {
return "@Url.Action("DeleteBlog","Admin")/" + blog.id;
},
contentType: 'application/json; charset=utf-8',
type: "DELETE"
}, و این بخش :
$("#report-grid").kendoGrid({
dataSource: blogDataSource,
autoBind: true,
scrollable: false,
pageable: true,
sortable: true,
filterable: true,
reorderable: true,
selectable: true,
editable: {
confirmation: "آیا مایل به حذف ردیف انتخابی هستید؟",
destroy: true, // whether or not to delete item when button is clicked
mode: "popup" // options are "incell", "inline", and "popup" اینم کدهای اکشن متد Delete بنده :
[HttpDelete]
[ValidateAntiForgeryToken]
public async Task<IActionResult> DeleteBlog(long id)
{
var blog = _blogRepository.Get(id);
if (blog == null)
return NotFound();
blog.IsDeleted = true;
_blogRepository.Update(blog);
await _unitOfWork.SaveAsync();
return Json(blog);
} public IActionResult CurrentPostTags(int blogID)
{
var dataString = this.HttpContext.GetJsonDataFromQueryString();
var request = JsonConvert.DeserializeObject<DataSourceRequest>(dataString);
var tags = _blogRepository.GetAllTags(blogID).OrderBy(s => s.Id);
var currenttags = _mapper.Map<IList<TagsViewModel>>(tags);
if (currenttags == null)
{
return NotFound();
}
return Json(currenttags.AsQueryable()
.ToDataSourceResult(request.Take, request.Skip, request.Sort,
request.Filter));
} $(function() {
var currentTagsDataSource = new kendo.data.DataSource({
transport: {
read: {
url: "@Url.Action("CurrentPostTags", "Admin")",
dataType: "json",
contentType: 'application/json; charset=utf-8',
type: 'GET',
data : { blogID: @BlogID }
}, var tags = _blogRepository.GetAllTags(blogID).OrderBy(s => s.Id);
var currenttags = _mapper.Map<IList<TagsViewModel>>(tags);
if (currenttags == null)
{
return NotFound();
}
return Json(currenttags.AsQueryable()
.ToDataSourceResult(request.Take, request.Skip, request.Sort,
request.Filter));