Passing Kendo Grid request from javascript to mvc controller method - javascript

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 ?

Related

string is empty after is post with jquery post in MVC controller

I want to post a string to the MVC controller and return a partial view. The view returns but the string shows empty.
My controller:
public PartialViewResult CreateServiceRateModal(string serviceId)
{
System.Diagnostics.Debug.WriteLine(serviceId);
//var a = JsonSerializer.Serialize();
ViewData["ServiceId"] = serviceId;
return PartialView("~/Views/ServicesManager/_CreateServiceRate.cshtml");
}
Jquery:
function CreateServiceRateModal() {
var Id = $('#ServiceId').val();
$.post('CreateServiceRateModal', JSON.stringify(Id)).done(function (data) {
$('#modal-placeholder').html(data);
$('#modal-placeholder').find('.modal').modal('show');
});
I have checked the Id before posting is not empty.
You need to pass it with a property name matching your controller method parameter name as an object, so change it to this, you can read more on the documentation (https://api.jquery.com/jquery.post/):
$.post('CreateServiceRateModal', { serviceId: Id }).done(function (data) {
$('#modal-placeholder').html(data);
$('#modal-placeholder').find('.modal').modal('show');
});

send multiple objects via ajax (using angular)

I have a list of user inputs in an object 'data'. (for e.g data.username, data.password, data.age)
i am passing the data object to backend like this using angular.
var submits = "=" + JSON.stringify(data);
$.ajax({
type: "POST",
url: serviceURL,
data: submits
});
I am passing two more objects. selections and grid. how can i pass all these three together in one ajax call ? or do i have to transfer it independently. will it affect the performance if i transfer these details separately.
can i do something like this to send the object together in one ajax call?
var data = {};
data[0] = data1;
data[1] = data2;
How can i retrieve it separately at the server side using c# if at all they are passed together.
Heres the 3 objects that i need to pass
data -->> ["Raul","New York","31"]
selections-->> ["dy.txt","my.txt","yy.txt"]
grid--> ["sesion","id"]
Assuming you have a view model like this in your server side
public class CreateUserViewModel
{
public string UserName{set;get;}
public string Location {set;get;}
public int Age {set;get;}
}
public class RegisterViewModel
{
public CreateUserViewModel User {set;get;}
public List<string> Selections {set;get;}
public List<string> Grid {set;get;}
}
and an MVC action method like this
public ActionResult Create(RegisterViewModel model)
{
// read model and save and return some JSON response
}
You can simply build the javascript object which matches the structure of the view model and post it using angualr's $http service. No need to worrry about setting content-Type or Json stringifying it. Angualr will take care of it.
var model={ User : {} ,Selections :[], Grid=[] };
model.User.Age =23;
model.User.UserName ="test";
model.User.Location="New York";
model.Selections.push("dy.txt");
model.Selections.push("some.txt");
model.Grid.push("session");
model.Grid.push("id");
var url="replcaeUrltoYourActionMethodHere";
$http.post(url, model)
.then(function(response)
{
// do something with the response
// var result= response.data
});
You can send multiple objects / variables in ajax with:
var submits = "=" + JSON.stringify(data);
$.ajax({
type: "POST",
url: serviceURL,
data: {submits : submits, data1:data1, data2:data2}
});
In your C# you can access data1 and 2 in the same way as you handle submits now.
Depending of what is in data1 and data2 you might need to stringify it first.
second option:
You can also if you want to (but it is more ugly) use the stringify on everything at once and only pass the string:
data = {};
data["data1"] = data1;
data["data2"] = data2;
var submits = "=" + JSON.stringify(data);
Are you using WebApi or MVC on the server? If so, the simplest approach would be to create a class which holds the 3 entities you need to send and leverage the built-in model-binding
So in your example you list what looks to be a user form, selections and grids. I'm not really sure what the last two are but an example Model might look something like this:
public class UserSubmissionViewModel
{
public UserSubmissionViewModel() { }
public UserFormModel User {get;set;}
public SelectionsModel Selections { get; set; }
public GridModel Grids { get; set; }
}
Then on your web api controller or your MVC controller you'd have a method such as this:
public async Task<IHttpActionResult> Submit(UserSubmissionViewModel model)
And your javascript would resemble something roughly like this:
var toSend = {"UserFormModel":data, "SelectionsModel":selections, "GridModel":grids};
$.ajax({
type:"POST",
data:toSend, //<--- you might need to JSON.stringify this, cant test this code at the moment
url:serviceURL //<-- Calls your Submit method on the controller
});

Posting a model with Kendo Grid read action

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();

How to send IEnumerable list from Ajax to Controller

I have a web application in MVC3 and i'm using Telerik Grid Batch Editing.
Batch Editing have save changes button which returns UPDATED COLUMNS to controller IEnumerable list like
[GridAction]
public ActionResult Update(IEnumerable<Customers> updated)
{
///user codes
}
but how to collect updated rows and make array send like IEnumerable list from Javascript with ajax to Controller ?
EDIT
I'm putting my view png
I just want to send updated rows data to Controller and Save Changes button can do this but before thje send values i just want to ask to user "Are you sure to Load?" and after the send data I want to refresh all the page
So i thinked to do this with ajax request because i'm also using batch editing with ajax requests
Do you have any exprience for this situation?
Use the AJAX POST as I have used in my Tested Javascript function as::
function TestAjax() {
var Test = [];
for (var i = 0; i < 5; i++) {
Test.push({ ID: i, Name: "RJ" });
}
$.ajax({
type: 'POST',
url: rootUrl('Home/TestPost'),
contentType: "application/json",
//data: { Test: JSON.stringify( data) },
data:JSON.stringify( {Test: Test}),
success: function (data) {
alert("Succeded");
}
});
}
And on Server Side(i.e. In Controller) use something Like::
public ActionResult TestPost(IEnumerable<TestViewModel> Test)
{
return Json(3);
}
The ViewModel Contains different propeties which are of different datatypes as::
public class TestViewModel
{
public long ID { get; set; }
public string Name { get; set; }
}
This is working fine. May be this will help you.

Can't send javascript object array to new page

I have a javascript array of objects that I am trying to send to my new view. I don't want to use AJAX - this is a new page altogether. I can't seem to figure out how to send the array to my controller action.
I have an action that returns an UploadFile object to my view, which is added to an array in javascript. When the user tries to continue to "review" the results, I'm sending that array of objects to the new page.
public ActionResult Review(List<UploadFile> model)
{
return View();
}
I still tried using AJAX but I encountered two problems: 1) I want a new page, I don't want it to stay on the same page, 2) The model is still null.
$('.js_btn-review').click(function () {
$.ajax({
url: '/Document/Review',
data: documents,
type: 'GET'
});
});
I'm not sure how to do this - I know I've done it before, but I can't remember how I did it. I even tried setting an element and serializing:
$('.js_btn-review').click(function () {
$("#documents").val(documents);
$.ajax({
url: '/Document/Review',
data: $("#documents").serialize(),
type: 'GET'
});
});
What am I doing wrong here?
As you didn't state the structure of the js variable documents I am assuming it is just an array of UploadFiles. Something along the lines of:
var documents = [];
for (var i = 0; i < 10; i++) {
var d = {
id: i,
title: i.toString()
};
documents.push(d);
}
Which you then taking and sending via ajax. This will not work as documents do not have a container so the URL for the GET will look something like /Document/Review?undefined=&undefined=&undefined=&undefined=&
By changing it to
var data = {
model: documents
};
$('.js_btn-review').click(function () {
$.ajax({
url: '/Home/Review',
data: data,
type: 'GET'
});
});
The models should be populated.
As for the view changing you will need to do something other than .ajax as just goes and gets the response. it doesn't change pages.
The parameter name should be the same as the name of the data being sent, so if the data object is called documents, your parameter in the controller should have the same name as follows.
public ActionResult Review(List<UploadFile> documents)
{
return View();
}
the Javascript for that
$('.js_btn-review').click(function () {
$.ajax({
url: '/Document/Review',
data: JSON.stringify( documents ),
type: 'Post'
});
});
Without AJAX
It's just like the PRG Pattern so you POST a form.
#{
List<UploadFile> list = new List<UploadFile> { ... };
}
#using(Html.BeginForm("Review", "Controller", FormMethod.Post, new { }))
{
for (int i = 0; i < list.Count(); i++)
{
#Html.HiddenFor(m => list[i]);
}
<input type="submit" value="Review" />
}
Controller Actions
[HttpPost]
public ActionResult Review(List<UploadFile> list)
{
TempData["Review_list"] = list;
return RedirectToAction("Review");
}
[HttpGet]
public ActionResult Review()
{
var list = TempData["Review_list] as List<UploadFile>;
return View(list);
}
If you don't need to process the list on the server
Don't bother with passing back and keep the list in javascript:
Store it in Web Storage like sessionStorage as JSON
Do a regular GET to navigate to your new page (e.g. Review)
Retrieve the list from sessionStorage and build the html

Categories