Kendo Datasource not sending string to Controller - kendo-ui

I am creating a CRUD application, My application is getting a string from from a Kendo input box, and will need to send it to my controller which is expecting a string that I am getting from my Jquery call. However, the string is not getting to my controller. I have tried various ways and I am not able to send it through my Transport. I have put break point and I can confirm that the value is being picked up in my Kendo Observable.
My Datasource
var client = new kendo.data.DataSource({
transport: {
read: {
url: "Client/SearchClient",
contentType: "application/json; charset=utf-8",
dataType: "json",
},
My Controller
public ActionResult SearchClient()
{
return View();
}
[HttpPost]
public ActionResult SearchClient(string name)
{
Repo repo = new Repo();
var result = repo.GetClient();
return Json(new
{
list = result,
count = result.Count
}, JsonRequestBehavior.AllowGet);
}
This is my Kendo Observable
var viewModel = kendo.observable({
client: {
clientName: "",
clientNumber: "",
clientType: "",
},
dropdownlist: ["HCC", "Tax", "Audit", "Advisory"],
create: function (e) {
var userRequest = $("#clientname").val();
if (userRequest) {
client.read(userRequest);
}
if (!userRequest)
alert("Please Enter Client Name")
}
});

Search Client method wants POST, not GET? The default will be GET. Either change your api method to use HttpGet, or change the transport to method: "post" for read.
var client = new kendo.data.DataSource({
transport: {
read: {
url: "Client/SearchClient",
contentType: "application/json; charset=utf-8",
dataType: "json",
method: "post"
},

Related

Passing more then 1 value to webmethod using FormData via Ajax

I'm trying to pass the uploaded image + two additional parameters to my web service using the FormData method from my Ajax method as shown here:
var formData = new FormData();
formData.append('file', $('#photo')[0].files[0]);
formData.append('u', "test");
formData.append('s', "Testing");
My ajax call is outlined like so:
$.ajax({
url: "/admin/WebService/test.asmx/UploadImage",
type: "POST",
processData: false,
contentType: false,
data: formData,
success: function (response) {
console.log(response);
},
error: function (er) {
alert(er);
}
});
Which calls this webmethod:
[WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public string UploadImage()
{
if (System.Web.HttpContext.Current.Request.Files.AllKeys.Any())
{
var t= System.Web.HttpContext.Current.Request.Files["s"];
var c= System.Web.HttpContext.Current.Request.Files["u"];
var p = System.Web.HttpContext.Current.Request.Files["file"];
}
else
{
return "Error";
}
return "Error";
}
The issue I'm having is the parameters 'u' and 's' are null yet when referencing file I'm able to get its value.
Whilst searching the web I was under the impression you can specify as many key/values are required when using this approach unless I have been misinformed? can someone please shed some light into why these two parameters are null? Thanks in advance.
This works for me:
JavaScript
var formData = new FormData();
formData.append("UserId", userId);
formData.append("RequestPhoto", imageFile);
formData.append("RequestVoiceRecord", voiceFile);
formData.append("Latitude", latitude);
formData.append("Longitude", longtitude);
$.ajax({
type: "POST",
url: "/User/CreateRequest",
data: formData,
contentType: false,
processData: false,
success: function () {
alert("OK");
},
error: function () {
alert("Error");
}
});
Controller:
public class UserController : ApiController
{
[HttpPost]
public int CreateRequest()
{
// HttpResponseMessage result = null;
var httpRequest = HttpContext.Current.Request;
var req = new UserRequest
{
UserId = Guid.Parse(httpRequest.Form["UserId"]),
Photo = httpRequest.Files["RequestPhoto"],
VoiceRecord = httpRequest.Files["RequestVoiceRecord"]
Latitude = float.Parse(httpRequest.Form["Latitude"]),
Longitude = float.Parse(httpRequest.Form["Longitude"]),
};
You should create one json instead of create this stuff, add whatever keys you want to sent via ajax.
var formData = {'u':'value','s':'value'}
$.ajax({
url: "/admin/WebService/test.asmx/UploadImage",
type: "POST",
processData: false,
contentType: false,
data: JDON.Stringify(formData),
success: function (response) {
console.log(response);
},
error: function (er) {
alert(er);
}
});
try using this way.

How to prevent to get __RequestVerificationToken automatically in ajax?

I'm using asp.net mvc 5 and creating a form to login via ajax (server side requires [ValidateAntiForgeryToken]).
I don't have any problem in the View:
#using (Html.BeginForm("Login", "Account", FormMethod.Post, new { id = "loginForm" }))
{
#Html.AntiForgeryToken()
<!-- more tags -->
}
but I'm getting error message
The anti-forgery token could not be decrypted.
when I try to call this method:
//u is url string, f is FormData()
var submit = function (u, f) {
$.ajax({
url: u,
type: 'POST',
data: { __RequestVerificationToken: $($('#loginForm input[name=__RequestVerificationToken]')[0]).val(), model: f },
processData: false,
contentType: false
}).done(function (data) {
if (data.success) {
/* successfull login */
Custombox.close();
window.location.href = '/?type=promotion'
} else {
/* server returned exception message */
$('div.validation-summary-valid').html(data.ex)
}
}).fail(function (error) {
/* connect to server failure */
$('div.validation-summary-valid').html(data.ex)
})
};
Here is the Headers snapshot:
Why duplicate __RequestVerificationToken and how to fix it?
I guess you are sending it twice.
Once explicitly by reading the input field value and second inside the f variable, which i assumes is a serialized form.
Solution : Remove the part where you are sending it explicitly.
You can simply serialize your form and send. This will include the RequestVerificationToken.
$(function () {
$("#yourSubmitBtnId").click(function (e) {
e.preventDefault();
var f = $("#loginForm");
var formData = JSON.stringify(f.serialize());
var u = f.attr("action");
$.ajax({
url: u,
type: 'POST',
data:formData,
processData: false,
contentType: "application/json",
}).done(function (data) {
//do something
}).fail(function (error) {
//do something else
});
});
});

How to implemnent Paging with kendo pager on demand web api call

Am calling web api method from view model and getting the 10 records per click. I want paging for kendo template.
this is my code:
// this is the web api method which gets 10 records per each call
function WebApiMethod(parameter)
{
var url = webApiUrl + 'api/{controller}/{methodname}';
var success = function(result)
{
}
CallWebApi(url, 'POST', success, parameter);
}
///this is the ajax call that am calling from webapimethod
function CallWebApi(url, type, successCallBack, data) {
jQuery.support.cors = true;
$.ajax({
cache: false,
type: type,
url: url,
data: JSON.stringify(data),
async: false,
contentType: 'application/json',
success: successCallBack,
error: function (xhr, err) {
}
});
}
///this is the kendo pager in which am biding the datasource
function KendoPager()
{
var pager = $("#pager").kendoPager({
dataSource: ViewModels["NameOfVM"].dataSource,
info: false,
change: function () {
ViewModels["NameOfVM"].pageIndex = pager.page();
}
}).data("kendoPager");
}
//this is the datasource am bind to kendopager
dataSource: new kendo.data.DataSource({
serverPaging:true,
pageSize:10,
})
Thanks in advance.

Confused with JSON string returned by webservice

I just started to play around with Kendo-UI, web services and JSON. First I created and deployed my asp.net web service (I did not plan to use WCF). I checked the ASMX file which returned the following result:
[
{"Id":"4e7dc3f8-db50-4978-be10-09808a6216a7","CompanyName":"company1"},
{"Id":"d156a2cd-1768-439e-98eb-134366a6c9be","CompanyName":"company2"},
{"Id":"7acba8b5-b773-4071-bfd5-2537d7d20e1e","CompanyName":"company3"}
]
I checked the above result with a web based JSON validator (copy/paste, not via calling the web service), which resulted in a successful parsing. So far everything seemed to be OK.
The next step was to populate a kendoDropDownList with the results:
var dataSource = new kendo.data.DataSource({
transport: {
read: {
url: "/scws/qpm.asmx/GetSuppliers",
dataType: "json"
}
}
});
$("#supplier").kendoDropDownList({
dataSource: dataSource,
dataValueField: "Id",
dataTextField: "CompanyName"
});
Well, it did not work. I tried several variations, until I gave up and tried to call my web service a different way, just for testing:
$.ajax({
url: "/scws/qpm.asmx/GetSuppliers",
type: "POST",
contentType: "application/json; charset=utf-8",
dataType: "json",
cache: false,
success: function (msg) {
// data is returned
},
error: function (xhr, status, error) {
// handle error
alert(status);
alert(xhr.status);
alert(xhr.responseText);
alert(error);
}
});
Well, I got a parser error (200). The response text is different from what I got with directly testing the ASMX file. The response text seems to be longer:
[
{"Id":"4e7dc3f8-db50-4978-be10-09808a6216a7","CompanyName":"company1"},
{"Id":"d156a2cd-1768-439e-98eb-134366a6c9be","CompanyName":"company2"},
{"Id":"7acba8b5-b773-4071-bfd5-2537d7d20e1e","CompanyName":"company3"}
]
{"d":null}
I am sure I did some basic thing very badly... I would appreciate your help.
Not know what your asmx method looks like, it's hard to say exactly. Here is a quick sample asmx I threw together. I did go ahead and switch my method to use a GET instead of a POST.
Webservice
[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[System.ComponentModel.ToolboxItem(false)]
[System.Web.Script.Services.ScriptService]
public class Service : System.Web.Services.WebService
{
[WebMethod]
[ScriptMethod (UseHttpGet = true, ResponseFormat = ResponseFormat.Json)]
public List<Person> GetPeople()
{
List<Person> people = new List<Person>();
people.Add(new Person() { Age = 21, Name = "Fred" });
people.Add(new Person() { Age = 31, Name = "Ted" });
people.Add(new Person() { Age = 41, Name = "Ned" });
people.Add(new Person() { Age = 51, Name = "Red" });
return people;
}
}
public class Person
{
public string Name { get; set; }
public int Age { get; set; }
}
Which returned this json
{"d":[{"__type":"ASMXTest.Person","Name":"Fred","Age":21},{"__type":"ASMXTest.Person","Name":"Ted","Age":31},{"__type":"ASMXTest.Person","Name":"Ned","Age":41},{"__type":"ASMXTest.Person","Name":"Red","Age":51}]}
Here is my kendo dataSource to access that webmethod
var dataSource = new kendo.data.DataSource({
transport: {
read: {
url: "Service.asmx/GetPeople",
dataType: "json",
contentType: "application/json; charset=utf-8"
}
},
schema: {
data: function (response) {
return response.d;
}
}
});
$("#grid").kendoGrid({
dataSource: dataSource,
columns: [
{ field: 'Name' },
{ field: 'Age' }
]
});
If this doesn't get you going, please post your asmx webmethod.
Thank you for your help and time. I am afraid the problem was with my webservice. Now its fine.

Kendo UI, Grid, modify Data before send

Is it possible to access and modify data in Kendo UI grid before updating?
Below is an example to illustrate what I need. The options.data contains the sent data but it is already formatted in string "models=%B7%22Id22%.... etc" not really convenient form.
dataSource = new kendo.data.DataSource({
transport: {
read: {
...
},
update: {
url: baseURL + "update",
beforeSend: function(xhr, options){
xhr.setRequestHeader('API-KEY', apikey );
var modifiedData = doSomething(options.data);
return modifiedData;
},
dataType: "json",
method: "POST",
dataFilter: function(data){
... some data recieved modification
return JSON.stringify(somedata);
},
complete: function(e) {
....
}
},
You should be able to use the parameterMap function, check the type for "update" and change the options.data anyway you want.
parameterMap: function(options, type) {
if(type === "update") {
options.someProperty = "somenewvalue";
}
return kendo.data.transports.odata.parameterMap(options, type);
}

Resources