Kendo UI DataSource Issue passing parameters to service - kendo-ui

I'm using Kendo UI Grid + DataSource and I'm facing some issues interacting with my service:
We have a service which should be called as follows:
/find?criteria[0].FieldName=Name&criteria[0].Value=Test&criteria[1].FieldName=Description&criteria[1].Value=MyDescription
How I can pass the parameters as such to my service from my datasource?

you have to use the parameterMap function like this:
var data = kendo.data.DataSource({
transport: {
// these are passed to $.ajax()
read: {
url: "/find",
dataType: 'json',
type: 'GET',
cache: false
},
update: {
// ...
},
destroy: {
// ...
},
create: {
// ...
},
//
parameterMap: function(options, type) {
// edit VARS passed to service here!
if (type === 'read') {
return {
'criteria[0].FieldName': options.name,
'criteria[0].Value': options.value
// ...
};
}
}
},
schema: {
model: MyModel,
type: 'json',
parse: function(response) {
// edit VARS coming from the server here!
// ...
return response;
}
}
});

If you are using client side Json binding. check: dataSource->transport->parameterMap property.
such as:
$(function () {
$("#grid").kendoGrid({
.....
dataSource: {
....
transport: {
parameterMap: function (data, operation) {
if (operation != "read") {
.....
return result;
} else {
//data sample: {"take":10,"skip":0,"page":1,"pageSize":10}
//alert(JSON.stringify(data)); //Need to insert custom parameters into data object here for read method routing. so, reconstruct this object.
data.CustomParameter1 = "#Model.Parameter1"; // Got value from MVC view model.
data.CustomParameter2 = "#Model.Parameter2"; // Got value from MVC view model.
return JSON.stringify(data); // Here using post. MVC controller action need "HttpPost"
}
}
}
}
MVC controller:
[HttpPost]
public ActionResult Read(int CustomParameter1, int CustomParameter2, int take, int skip, IEnumerable<Kendo.Mvc.Grid.CRUD.Models.Sort> sort, Kendo.Mvc.Grid.CRUD.Models.Filter filter)
{
.....
}
Corporated project sample in:
http://www.telerik.com/support/code-library/grid-bound-to-asp-net-mvc-action-methods---crud-operations

Related

Kendo DataSource catch server response

In my kendo dataSource > transport > update. I want to catch a server response status (refer image), but none of this methods trigger an alert. Any idea why?
update: {
url: "./getRevenueAccounts.php",
type: "POST",
data: function() {
return {
method: "editRevenueAccounts"
}
},
success: function(e) {
if(e.status == 'duplicate'){
alert('Trigger 1');
}
},
error: function(e) {
if (e.errorThrown == 'duplicate') {
alert("Trigger 2");
}else if(e.status == 'duplicate' ){
alert("Trigger 3")
}
},
complete: function (e) {
if(e.status == 'duplicate'){
alert('Trigger 4');
}
}
},
console.log(e) screen shot
Try the following code for your success function:
success: function(e) {
if(e.responseText.status == 'duplicate'){
alert('Trigger 1');
}
},
Essentially, you are looking at the status property when you should have been looking at the responseText property to get the status (which is another property on that object).
You need to make an ajax call inside the update function.
Like:
var dataSource = new kendo.data.DataSource({
transport: {
read: function(options) {
/* implementation omitted for brevity */
},
update: function(options) {
// make JSONP request to https://demos.telerik.com/kendo-ui/service/products/update
$.ajax({
url: "https://demos.telerik.com/kendo-ui/service/products/update",
dataType: "jsonp", // "jsonp" is required for cross-domain requests; use "json" for same-domain requests
// send the updated data items as the "models" service parameter encoded in JSON
data: {
models: kendo.stringify(options.data.models)
},
success: function(result) {
// notify the data source that the request succeeded
options.success(result);
},
error: function(result) {
// notify the data source that the request failed
options.error(result);
}
});
}
},
batch: true,
schema: {
model: { id: "ProductID" }
}
});
For more details please check this from telerik documentation: https://docs.telerik.com/kendo-ui/api/javascript/data/datasource/configuration/transport.update
Is not a good method to apply, but it works to fetch the response.
if(e.responseText=='{"status":"duplicate"}'){
kendo.alert('duplicate data');
}

Ajax post method returns undefined in .net mvc

I have this ajax post method in my code that returns undefined. I think its because I have not passed in any data, any help will be appreciated.
I have tried passing the url string using the #Url.Action Helper and passing data in as a parameter in the success parameter in the ajax method.
//jquery ajax post method
function SaveEvent(data) {
$.ajax({
type: "POST",
url: '#Url.Action("Bookings/SaveBooking")',
data: data,
success: function (data) {
if (data.status) {
//Refresh the calender
FetchEventAndRenderCalendar();
$('#myModalSave').modal('hide');
}
},
error: function (error) {
alert('Failed' + error.val );
}
})
}
//controller action
[HttpPost]
public JsonResult SaveBooking(Booking b)
{
var status = false;
using (ApplicationDbContext db = new ApplicationDbContext())
{
if (b.ID > 0)
{
//update the event
var v = db.Bookings.Where(a => a.ID == a.ID);
if (v != null)
{
v.SingleOrDefault().Subject = b.Subject;
v.SingleOrDefault().StartDate = b.StartDate;
v.SingleOrDefault().EndDate = b.EndDate;
v.SingleOrDefault().Description = b.Description;
v.SingleOrDefault().IsFullDay = b.IsFullDay;
v.SingleOrDefault().ThemeColor = b.ThemeColor;
}
else
{
db.Bookings.Add(b);
}
db.SaveChanges();
status = true;
}
}
return new JsonResult { Data = new { status } };
}
Before the ajax call, you should collect the data in object like,
var requestData= {
ModelField1: 'pass the value here',
ModelField2: 'pass the value here')
};
Please note, I have only added two fields but as per your class declaration, you can include all your fields.
it should be like :
function SaveEvent(data) {
$.ajax({
type: "POST",
url: '#Url.Action(Bookings,SaveBooking)',
data: JSON.stringify(requestData),
dataType: 'json',
contentType: 'application/json; charset=utf-8',
success: function (data) {
if (data.status) {
//Refresh the calender
FetchEventAndRenderCalendar();
$('#myModalSave').modal('hide');
}
},
error: function (error) {
alert('Failed' + error.val );
}
})
}
Try adding contentType:'Application/json', to your ajax and simply have:
return Json(status);
In your controller instead of JsonResult. As well as this, You will need to pass the data in the ajax code as a stringified Json such as:
data:JSON.stringify(data),
Also, is there nay reason in particular why it's a JsonResult method?

Not getting Json object (having a collection) correctly in controller using ajax call

I am sending a json object to controller via ajax call, data property of ajax call showing correct data. On post to controller's method -received parameter having collection and its count is showing perfectly but the properties inside the collection is not showing values.
Here is the code -
Controller-
[HttpPost]
public ActionResult ImageOperations(ImageProcessingModel imageProcessingModel)
{
return Json("sucess");
}
Model-
public class ImageProcessingModel
{
public string Source { get; set; }
private List<ThumbnailImageSubTaskModel> _thumbnailImageSubTaskModel;
public List<ThumbnailImageSubTaskModel> ThumbnailImageSubTaskModel
{
get
{
if (_thumbnailImageSubTaskModel == null)
{
_thumbnailImageSubTaskModel = new List<ThumbnailImageSubTaskModel>();
}
return _thumbnailImageSubTaskModel;
}
}
}
js-
var ImageProcessingModel =
{
"Source": "test",
"ThumbnailImageSubTaskModel":allThumbnails.allItems()
}
allThumnails.allItems is ko.observableArray() which having values.
$.ajax({
url: '/ImageProcessingTask/ImageOperations',
type: 'Post',
data: ImageProcessingModel,
success: function (data, status) {
processEscapeKeyPress = true;
var fn = window[successCallback];
fn(data, passDataToCallback);
},
error: function (xhr, desc, err) {
alert(err);
processEscapeKeyPress = true;
processAjaxError(xhr, desc, err);
},
});
here ImageProcessingModel having all values and source is simple a string so this value is coming in the controller only the ThumbnailImageSubTaskModel showing counts but not its value.
Thanks!!
A common problem encoutered with sending JSON through AJAX to MVC. Many forget to set the type of data in their AJAX request.
Try setting the datatype and contentType:
$.ajax({
url: '/ImageProcessingTask/ImageOperations',
type: 'Post',
**contentType: 'application/json; charset=UTF-8',
dataType: 'json',**
data: ImageProcessingModel,
success: function (data, status) {
processEscapeKeyPress = true;
var fn = window[successCallback];
fn(data, passDataToCallback);
},
error: function (xhr, desc, err) {
alert(err);
processEscapeKeyPress = true;
processAjaxError(xhr, desc, err);
},
});

Pass serialized form to Action and bind to model

I am trying to bind model received from Ajax call but that do not work. Maybe someone could help me?
I am calling ValidateFile Action using Ajax
$.ajax({
url: '#Url.Action("ValidateFile", "Converter")',
data: ({ file: fileName, formData: serializedForm }),
type: 'POST',
success: function (response) {
if (response.result) {
} else {
RemoveFile(fileName);
}
}
});
The Fiddler show such query
file=!!!SP+Design!!!.txt&formData%5BEmail%5D=tomas%40mydomain.com
I receive data in my Action with file parameter populated but formData.Email property is always Null
[HttpPost]
public JsonResult ValidateFile(string file, UploadOptionModel formData)
{
}
My UploadOptionModel model
namespace PC.Models
{
public class UploadOptionModel
{
public string Email { get; set; }
}
}
Form which I am trying to serialize
#model PC.Models.UploadOptionModel
#using (Html.BeginForm())
{
#Html.EditorFor(p => p.Email)
}
JS Serialization function
function serializeForm() {
var data = $("form").serializeArray();
var formData = {};
for (var i = 0; i < data.length; i++) {
formData[data[i].name] = data[i].value;
}
return formData;
}
You need to JSON encode the data and set the content type to JSON for the model binder to work with JSON. So try this:
$.ajax({
url: '#Url.Action("ValidateFile", "Converter")',
data: JSON.stringify({ file: fileName, formData: serializedForm }),
contentType: 'application/json',
type: 'POST',
success: function (response) {
if (response.result) {
} else {
RemoveFile(fileName);
}
}
});

Acessing ViewData in javascript?

I want to access view data In Java script in following code
public virtual ActionResult Edit(MyModel _MyModel)
{
//some Code
if (true..)
{
ViewData["Messages"] = "Data Updated Sucessfully";
}
else
{
ViewData["Messages"] = "you cannot Updated data";
}
return View();
}
In javascript
function SaveData() {
$("#btnSave").click(function () {
// $('#divLoadImage').show();
// $('#divOverlay').show();
// debugger;
$.ajax({
type: "POST",
url: "Admin/Edit/",
data: "",
complete: function () {
alert(ViewData["Messages"]);
}
});
});
}
it give me no value in alert..
You need to encode it using for example the JavaScriptSerializer class:
function SaveData() {
$("#btnSave").click(function () {
$.ajax({
type: "POST",
url: "Admin/Edit/",
data: "",
complete: function () {
alert(#Html.Raw(new JavaScriptSerializer().Serialize(ViewData["Messages"])));
}
});
});
}
or use simple quotes but be careful as this might break if the message contains quote so I wouldn't recommend you this:
alert('#ViewData["Messages"]');

Resources