I'm trying to add a search form to my page that updates the Kendo Grid. How should I send the Ajax call, so the ASP.NET MVC Model Binder be able to work?
This is my Ajax call:
var grid = $("#SearchSheetHeads").data('kendoGrid');
var data = $("#SearchSheet").serialize();
grid.dataSource.transport.options.read.url = "#Url.Action("SearchHeaderRead", "Sheet")";
grid.dataSource.transport.options.read.data = data;
grid.dataSource.transport.options.read.dataType = 'json';
grid.dataSource.transport.options.read.contentType = "application/json";
grid.dataSource.transport.options.read.type = "POST";
grid.dataSource.fetch();
I've also tried it by stringify method and removing contentType.
And this is my Action signature:
public ActionResult SearchHeaderRead([DataSourceRequest] DataSourceRequest request, SearchSheetHeaderViewModel model)
And the request looks like this:
Can't test it at the moment, but try something like this:
var grid = $("#SearchSheetHeads").data('kendoGrid');
var data = $("#SearchSheet").serialize();
$.ajax(
{
type: 'POST',
url: '#Url.Action("SearchHeaderRead", "Sheet")',
dataType: 'json',
data: { model: data },
success: function (result) {
grid.dataSource.data(result.Data);
}
});
data: { model: data } is probably the important part for you.
Can you change the second line as given below and try it out
var data = $("#SearchSheetHeads").data('kendoGrid').dataSource.data();
Related
I'm trying to pass filters of kendogrid to mvc controller, but something is going wrong. I tried the way in this link.
This is javascript side:
var grid = $(gridId).data("kendoGrid"),
remote = '...',
parameterMap = grid.dataSource.transport.parameterMap,
requestObj = {
sort: grid.dataSource.sort(),
filter: grid.dataSource.filter()
},
postData = parameterMap(requestObj),
success = function(){...};
$.post(remote, postData, success);
This is controller side:
[HttpPost]
public ActionResult GetSumOfInvoiceAmount([DataSourceRequest]DataSourceRequest request){...}
Although there is some filter in kendo grid, it seems as no filter in controller method. What is wrong here ?
I am using the Map() functionality in ES6 to create a list of keypair values, making an ID number to a boolean value. I want to pass this Javascript object to an MVC 4 Controller.
Here's my Javascript:
var bankHolidays = new Map();
$('.bank-holiday-switch').each(function () {
var id = $(this).attr('id');
var isChecked = $(this).is(':checked');
bankHolidays.set(id, isChecked);
});
$.ajax({
url: '/AdminPanel/Settings/SaveBankHolidays',
type: 'POST',
data: { bankHolidays: bankHolidays },
success: function (result) {
alert("Success");
}
});
I can console.log() the map object and see that it's being created as intended. However, when I pass it to this MVC Controller:
[HttpPost]
public JsonResult SaveBankHolidays(Dictionary<int, bool> bankHolidays)
{
// DO stuff
}
..no error is thrown, but it just says the bankHolidays dictionary has 0 values in it. I can call other Actions in that Controller without issue. I have tried many different combinations of Dictionary<string, bool> to no avail.
Can somebody tell me what I am doing wrong?
In a http negotiation, xhr in this case, we must send strings, so you need some string representation of Map(), the best option, in my opinion, is to use a JSON stringify in some way, because the parse of JSON have a broad support among server side code:
var bankHolidays = new Map();
bankHolidays.set(1, 2);
bankHolidays.set(3, 4);
var result = JSON.stringify([...bankHolidays]);
console.log(result)
In your code something like :
$.ajax({
url: '/AdminPanel/Settings/SaveBankHolidays',
type: 'POST',
data: JSON.stringify([...bankHolidays]),
success: function (result) {
alert("Success");
}
});
In backend you have to parse the response, see this.
I try to pass many values to Action in MVC but, user is always null.
var form = $('form');
$.ajax({
type: "POST",
url: '#Url.Content("~/User/UpdateUser")',
data: { user: form.serialize(), NameOfCare: care },
success: function (result) {
if (result == "Ok") {
document.location.href = '#Url.Content("~/User/Index")';
}
}
});
how to pass form with many values in Ajax ?
First of all, you have to use #Url.Action instead #Url.Content because you have to send your form data to a controller in order to process data.
.serialize method encode a set of form elements as a string for submission.
You should use this: data:form.serialize() + "&NameOfCare="+care.
On server-side your method should looks like this:
public ActionResult(UserViewModel user,string NameOfCare){
}
user object will be filled with your data , using Model Binding
you are sending a serialized object while it's actually a string. try below example. The action will de-serialize the string automatically.
function load() {
var dataT = $("#searchform").serialize();
var urlx = "#Url.Action("SR15Fetch", "SR15", new { area = "SALES" })";
debugger;
$.ajax({
type: "GET",
url: urlx,
data: dataT,
cache: false,
success: HandellerOnSuccess,
error: HandellerOnFailer,
beforeSend: Ajax_beforeSend(),
complete: Ajax_Complete(),
});
}
I asked a question to fill in the model data on the client, into arrays.
Add items to JSON objects
Now my problem is how to post it to the controller. I have tried this:
public ActionResult ItemRequest (Model1 model)
{
////
}
but it never gets there.
I'm trying with an AJAX request to send it:
function sendRequest() {
jsonData.items = itemArray;
$.ajax({
url: '#Url.Action("ItemRequest")',
type: 'POST',
data: JSON.stringify(jsonData),
///// and so on
}
But the action result is never invoked. I can drop the 'JSON.stringify' and it makes no difference. Any ideas on how to post this object to the controller?
If I make a psuedo model in JS it works fine, but I don't want to have to make this model, I'd rather use the model passed to the page.
function itemModel () {
var self = this;
this.itemNumber = $("#itemNumberId").val();
/// etc.
self.items = [];
}
function itemsModel () {
var self = this;
this.itemNumber = $("#itemNumberId").val();
/// etc
}
then
var itemCount = 0;
function addItem() {
var newItem = new itemModel();
newItem.items[itemCount] = newItem;
/// etc
}
This works fine.
I send the array itemModel the same way with a JSON.stringify directly into the controller method
public ActionResult ItemRequest(ItemModel model)
We are using this to send Data to API controller Methods on our internal test sides:
It's probably not the prettiest solution, but it can be used on any page.
What data should be sent:
$("#btnSend").click(function () {call("controller/method", {ParamName: $("#field").val()}); });
To send the data to a controller:
$(document).ready(function () {
var call = function (method, requestData, resultHandler) {
var url = method.substring(0, 1) == "/api/" + method;
$.ajax({
url: url,
dataType: 'json',
data: JSON.stringify(requestData),
type: 'POST',
contentType: 'application/json',
success: function (data) {
var isSuccess = data.Status == "success";
$("#jsonResponse").val(FormatJSON(data));
if (isSuccess && jQuery.isFunction(resultHandler)) {
resultHandler(data);
}
}
});
};
I have a form with input field which can be accessed like
var algorithm = document.forms["algoForm"]["algorithm"].value;
var input = document.forms["algoForm"]["input"].value;
and earlier call was
document.forms["algoForm"].submit();
and form was
<form name="algoForm" method="post" action="run.do">
It all run fine
Now I wanted convert it to the ajax call so that I can use the returned data from java code on the same page. So I used soemthing like
var algorithm = document.forms["algoForm"]["algorithm"].value;
var input = document.forms["algoForm"]["input"].value;
var data = 'algorithm = ' + algorithm + '&input = ' + input;
$.ajax(
{
url: "run.do",
type: "POST",
data: data,
success: onSuccess(tableData)
{ //line 75
alert(tableData);
}
}
);
However the above code doesn't run. Please help me make it run
Let's use jQuery's serialize to get the data out of the form and then use the jQuery's ajax function to send the data to the server:
var data = $("form[name=algoForm]").serialize();
$.ajax({
url: "run.do",
type: "POST",
data: data,
success: function(tableData){
alert(tableData);
}
});
data expects a literal object, so you need:
var data = {
'algorithm': algorithm,
'input': input
};
Instead of retrieving all the parameter value and then sending them separately (which can be done server side as well, using below code), Use this:
var $form = $("#divId").closest('form');
data = $form.serializeArray();
jqxhr = $.post("SERVLET_URL', data )
.success(function() {
if(jqxhr.responseText != ""){
//on response
}
});
}
divId is id of the div containing this form.
This code will send all the form parameters to your servlet. Now you can use request.getParameter in your servlet to get all the individual fields value on your servlet.
You can easily convert above jquery post to jquery ajax.
Hope this helps :)
// patching FORM - the style of data handling on server can remain untouched
$("#my-form").on("submit", function(evt) {
var data = {};
var $form = $(evt.target);
var arr = $form.serializeArray(); // an array of all form items
for (var i=0; i<arr.length; i++) { // transforming the array to object
data[arr[i].name] = arr[i].value;
}
data.return_type = "json"; // optional identifier - you can handle it on server and respond with JSON instead of HTML output
$.ajax({
url: $form.attr('action') || document.URL, // server script from form action attribute or document URL (if action is empty or not specified)
type: $form.attr('method') || 'get', // method by form method or GET if not specified
dataType: 'json', // we expect JSON in response
data: data // object with all form items
}).done(function(respond) {
console.log("data handled on server - response:", respond);
// your code (after saving)
}).fail(function(){
alert("Server connection failed!");
});
return false; // suppress default submit action
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
I don't know how but this one runs well,
var algorithm = document.forms["algoForm"]["algorithm"].value;
var input = document.forms["algoForm"]["input"].value;
$.post('run.do', {
algorithm : algorithm,
input : input
}, function(data) {
alert(data);
}
);