ajax other parameter is null? - asp.net-mvc

why my other paramter is null. "date" and "ids" is null while my "postedFile" and "amount" has a data. but when i try to removed "postedFile" parameter. the ids and date has a value. and it works fine. but i need the postedfile parameter
My Script
var ids = [];
function add(id, isChecked) {
if (isChecked) {
ids.push(id);
}
else {
var i = ids.indexOf(id);
ids.splice(i, 1);
}
}
function saveSelected() {
//var shipmentId = $('#c-shipment-id').val();
var date = $('#Date').val();
var amount = $('#Amount').val();
//var ImageFile = $('#imageUploadForm').val();
$('#imageUploadForm').on("change", function () {
var formdata = new FormData($('form').get(0));
CallService(formdata);
});
function CallService(postedFile) {
$.ajax({
url: '#Url.Action("index", "payment")',
type: 'POST',
data: { ids: ids, amount: amount, date: date, postedFile: postedFile },
cache: false,
processData: false,
contentType: false,
traditional: false,
dataType:"json",
success: function (data) {
alert("Success");
}
});
}
}
My Controller
public ActionResult Index(int?[] ids, decimal? amount, DateTime? date, HttpPostedFileBase postedFile)
{
return View();
}

As the comments above, I guess you could try to pass all the values with parameters, instead of the variables, like: CallService(formdata, ids, amount, date). It may works.
To answer your secondary question - Fetch all selected IDs in a table with a checkbox column:
Fisrt, add the ID into the checkbox's ID in the view, e.g.:
foreach (var m in Model.Data)
{
row++;
<tr class="#(row % 2 == 0 ? "alter" : "")">
<td class="first">
<input id="chk_#m.ID" type="checkbox" onclick="js_selone(this)" />
</td>
...
Then, Create a JS method getSelVal() to fetch all selected IDs and return an combined string with ,, e.g.: 1,2,3.
$.fn.getSelVal = function () {
for (var e = "", t = $("input[type=checkbox]", this), n = 0; n < t.length; n++) t[n].checked && (e += "," + js_getid(t[n].id));
return e.Trim(",");
}
Finally, you can call the method and pass the ids or ids.toString().split(',') to AJAX request:
ids = $('.table td').getSelVal().toString().split(',');
CallService(formdata, ids, amount, date)
function CallService(postedFile, ids, amount, date) {
$.ajax({
url: '#Url.Action("index", "payment")',
type: 'POST',
data: { ids: ids, amount: amount, date: date, postedFile: postedFile },
cache: false,
processData: false,
contentType: false,
traditional: false,
dataType:"json",
success: function (data) {
alert("Success");
}
});

Related

How can I get the selected checkbox in kendo grid?

I have Kendogrid grid that I get the data by JSON for the URL that I have and activate Selection mode as I found the kendo grid documentation, but I am trying to get the selected data from kendo grid, try some methods in javascript but not yet I have been able to do it. If someone can help me?
$(document).ready(function () {
$("#grid").kendoGrid({
toolbar: ["excel"],
excel: {
fileName: "user.xlsx",
filterable: true
},
dataSource: {
transport: {
read: {
url: `/user`
}
},
schema: {
data: function (response) {
return response.permisos;
},
model: {
fields: {
id: { type: "number" },
nombre: { type: "string" },
descripcion: { type: "string" }
}
}
},
pageSize: 20
},
height: 550,
scrollable: false,
sortable: true,
filterable: true,
pageable: true,
persistSelection: true,
change: onChange,
columns: [
{ selectable: true, width: "50px" },
{ field: "id", title: "Id" },
{ field: "nombre", title: "Nombre" },
{ field: "descripcion", title: "Descripción" }
]
});
$("#grid").data("kendoGrid").wrapper.find(".k-grid-header-wrap").off("scroll.kendoGrid");
});
I found two solutions, the first one is activating the change: onchange, one can obtain the selected checkboxes, each time one selects. What I'm doing is going through the checkboxes and saving them in a list
function onchange(e) {
var permiso = [];
var numero = 0;
var rows = e.sender.select();
rows.each(function (e) {
var grid = $("#grid").data("kendogrid");
var dataitem = grid.dataitem(this);
var recibir = dataitem;
console.log(dataitem);
console.log("dato recibido" + recibir.id);
permiso.push(recibir.id);
})
console.log("largo: " + permiso.length);
for (var i = 0; i < permiso.length; i++) {
console.log("array: " + permiso[i]);
}
And the other way is that you added a button that activates the event to go through the grid to get the checkbox, which is the best for me
$("#saveChanges").kendoButton({
click: function (e) {
var permiso = [];
var entityGrid = $("#grid").data("kendoGrid");
var rows = entityGrid.select();
rows.each(function (index, row) {
var selectedItem = entityGrid.dataItem(row);
var recibir = selectedItem;
console.log(selectedItem);
console.log("Dato recibido rows.each" + recibir.id);
permiso.push(recibir.id);
});
for (var i = 0; i < permiso.length; i++) {
console.log("List obtenido por el boton: " + permiso[i]);
}
var RolPermisos = { rolId: $("#IdRol").val() , permisos: permiso };
$.ajax({
type: 'POST',
contentType: 'application/json; charset=utf-8',
url: '../../Roles/api/Ui/',
dataType: 'json',
data: $.toJSON(lineItems),
success: function (result) {
if (result) {
alert('Success');
}
else {
alert('Failure');
}
}
});
}
})
My English is not so good, I hope you get the answer.

select2 + large number of records

I am using select2 dropdown. It's working fine for smaller number of items.
But when the list is huge (more than 40000 items) it really slows down. It's slowest in IE.
Otherwise simple Dropdownlist works very fast, till 1000 records. Are there any workarounds for this situation?
///////////////**** Jquery Code *******///////////////
var CompanypageSize = 10;
function initCompanies() {
var defaultTxtOnInit = 'a';
$("#DefaultCompanyId").select2({
allowClear: true,
ajax: {
url: "/SignUpTemplate/GetCompanies",
dataType: 'json',
delay: 250,
global: false,
data: function (params) {
params.page = params.page || 1;
return {
keyword: params.term ? params.term : defaultTxtOnInit,
pageSize: CompanypageSize,
page: params.page
};
},
processResults: function (data, params) {
params.page = params.page || 1;
return {
results: data.result,
pagination: {
more: (params.page * CompanypageSize) < data.Counts
}
};
},
cache: true
},
placeholder: {
id: '0', // the value of the option
text: '--Select Company--'
},
width: '100%',
//minimumInputLength: 3,
});
}
//////////******* Have to initialise in .ready *******///////////////
$(document).ready(function () {
initCompanies();
});
//////////******* C# code :: Controller is : SignUpTemplateController************/////
public JsonResult GetCompanies(string keyword, int? pageSize, int? page)
{
int totalCount = 0;
if (!string.IsNullOrWhiteSpace(keyword))
{
List<Companies> listCompanies = Companies.GetAll(this.CurrentTenant, (keyword ?? string.Empty).Trim(), false, 11, page.Value, pageSize.Value, ref totalCount, null, null, null, null, null).ToList();
var list = listCompanies.Select(x => new { text = x.CompanyName, id = x.CompanyId }).ToList();
return Json(new { result = list, Counts = totalCount }, JsonRequestBehavior.AllowGet);
}
return Json(null, JsonRequestBehavior.AllowGet);
}

Devexpress MVC5 Grid GetRowKey(e.visibleIndex) returns always null

Hi everyone I am trying to get the primary key of the selected row to send it to the server later here is the code:
This the mainpage
<script type="text/javascript">
function OnRowClick(s, e) {
var grid = MVCxClientGridView.Cast(s);
var key = grid.GetRowKey(e.visibleIndex);
console.log(key);
$.ajax({
url: '#Url.Action("FundDetails", "Fund")',
type: "POST",
dataType: "text",
traditional: true,
data: { rowKey: key },
success: function (data) {
console.log(data);
},
error: function (xhr, textStatus, errorThrown) {
alert('Request Status: ' + xhr.status + '; Status Text: ' + textStatus +
'; Error: ' + errorThrown);
}
});
}
</script>
<div>
#Html.Partial("_FundsList", Model)
</div>
And this is the partial view that contains the Grid
#Html.DevExpress().GridView(settings =>
{
settings.Name = "FundGrid";
settings.CallbackRouteValues = new { Controller = "Fund", Action =
"FundsList" };
settings.Width = 450;
settings.Columns.Add("codeIsin");
settings.Columns.Add("fundLabel");
settings.Columns.Add("variation");
settings.Columns.Add("ClassNiv1");
settings.SettingsBehavior.AllowSelectByRowClick = true;
settings.SettingsBehavior.AllowSelectSingleRowOnly = true;
settings.ClientSideEvents.RowClick = "OnRowClick";
}).Bind(Model).GetHtml()
the problem is that the key value is always null:
var key = grid.GetRowKey(e.visibleIndex); ==> always Null
PS : e.visibleIndex is not null.
The GetRowKey method explains how null value returned:
If the index passed via the visibleIndex parameter is wrong, or the
ASPxGridBase.KeyFieldName property is not set, null is returned.
It is possible that you need to set KeyFieldName which refers to primary key and/or identity field (with unique value) in the GridView, like this example:
#Html.DevExpress().GridView(settings =>
{
settings.Name = "FundGrid";
settings.CallbackRouteValues = new { Controller = "Fund", Action = "FundsList" };
settings.Width = 450;
settings.Columns.Add("codeIsin");
settings.Columns.Add("fundLabel");
settings.Columns.Add("variation");
settings.Columns.Add("ClassNiv1");
// set primary/identity key field to determine selected row index
settings.KeyFieldName = "codeIsIn";
settings.SettingsBehavior.AllowSelectByRowClick = true;
settings.SettingsBehavior.AllowSelectSingleRowOnly = true;
settings.ClientSideEvents.RowClick = "OnRowClick";
}).Bind(Model).GetHtml()
Also you can put null value checking with if condition before executing AJAX call to ensure key field value passed properly:
var key = grid.GetRowKey(e.visibleIndex);
if (key != null)
{
$.ajax({
url: '#Url.Action("FundDetails", "Fund")',
type: "POST",
data: { rowKey: key },
// other AJAX settings
success: function (data) {
// do something
},
error: function (xhr, textStatus, errorThrown) {
// error handling
}
});
}

Knockout-Kendo dropdownlist Ajax observableArray get selected item name

My application is MVC 5, I use the following Knockout-kendo dropdown list:
<input data-bind="kendoDropDownList: { dataTextField: 'name', dataValueField: 'id', data: foodgroups, value: foodgroup }" />
var ViewModel = function () {
var self = this;
this.foodgroups = ko.observableArray([
{ id: "1", name: "apple" },
{ id: "2", name: "orange" },
{ id: "3", name: "banana" }
]);
var foodgroup =
{
name: self.name,
id: self.id
};
this.foodgroup = ko.observable();
ko.bindingHandlers.kendoDropDownList.options.optionLabel = " - Select -";
this.foodgroup.subscribe(function (newValue) {
newValue = ko.utils.arrayFirst(self.foodgroups(), function (choice) {
return choice.id === newValue;
});
$("#object").html(JSON.stringify(newValue));
alert(newValue.name);
});
};
ko.applyBindings(new ViewModel());
It works great, thanks to this answer Knockout Kendo dropdownlist get text of selected item
However when I changed the observableArray to Ajax:
this.foodgroups = ko.observableArray([]),
$.ajax({
type: "GET",
url: '/Meals/GetFoodGroups',
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data) {
self.foodgroups(data);
},
error: function (err) {
alert(err.status + " : " + err.statusText);
}
});
Controller - get the table from ms sql server:
public JsonResult GetFoodGroups()
{
var data = db.FoodGroups.Select(c => new
{
id = c.FoodGroupID,
name = c.FoodGroupName
}).ToList();
return Json(data, JsonRequestBehavior.AllowGet);
}
I get this error when I alert the item name
Unable to get property 'name' of undefined or null reference
What is the difference between hardcoding the array items from using Ajax.
The 'id' field has string datatype in hard coded array.
The 'id' field has number datatype in ajax array.
.
So, the 'id' field has different datatypes in both arrays. However in-condition you have used === operator so it checks value as well as datatype.
For ajax array value is same but its datatype is different so its not returning result.
Let me know if any concern.

Kendo UI Grid not showing JSON data

I am facing this problem for quite a while now with the problem that I am unable to bind JSON data that my controller action is passing to the kendo UI Grid, there were few JavaScript issues before but now they are gone but still my grid is not showing any results:
In Model:
public object GetResult(string id)
{
var sqlCom = new SqlCommand("SELECT [No],[Desc],[Date],[Height],[Final] FROM [cr_form] WHERE [uId]=#id;", sqlConn);
sqlCom.Parameters.AddWithValue("#id", id);
StringBuilder sb = new StringBuilder();
StringWriter sw = new StringWriter(sb);
JsonWriter jsonWriter = new JsonTextWriter(sw);
var rcrds = GETSQLRESULTS(sqlCom);
try
{
int i = 0;
if (rcrds != null || rcrds.HasRows)
{
//jsonWriter.WriteStartObject();
while (rcrds.Read())
{
jsonWriter.WriteStartObject(); //Changed
for (int j = 0; j < rcrds.FieldCount; j++)
{
jsonWriter.WritePropertyName(rcrds.GetName(j)); // column name
jsonWriter.WriteValue(rcrds.GetValue(j)); // value in column
}
i++;
jsonWriter.WriteEndObject(); //Changed
}
//jsonWriter.WriteEndObject();
}
}
catch (Exception ex) { }
return jsonWriter;
}
In Controller:
public ActionResult GetRecords()
{
var usrObj = new User();
var jsnRslt = usrObj.GetResult(Session["Id"].ToString());
//Till here jsnRslt contains this string: “{"No":null,"Desc":"asfasfasfasfasfasfasfasfasfasfasfasf","Date":"2013-03-27T00:00:00","Height":0,"Final":null,"No":null,"Desc":"etwetwetwetwet","Date":"2013-03-27T00:00:00","Height":0,"Final":0,"No":null,"Desc":"asfasfasfskfjklajsfkjasklfjklasjfklajsfkljaklsfjklasjfkljasfkljlasf","Date":"2013-03-27T00:00:00","Height":0,"Final":0,"No":null,"Desc":"askjfkajsfklaskjfkajsfklaskjfkajsfklaskjfkajsfklaskjfkajsfklaskjfkajsfklaskjfkajsfklaskjfkajsfklaskjfkajsfklaskjfkajsfklaskjfkajsfklaskjfkajsfkl","Date":"2013-03-27T00:00:00","Height":0,"Final":0,"No":null,"Desc":"safasfasfasfasfasf","Date":"2013-03-27T00:00:00","Height":0,"Final":0,"No":null,"Desc":"asfasf","Date":"2013-03-27T00:00:00","Height":0,"Final":0,"No":null,"Desc":"asfasfasf","Date":"2013-03-27T00:00:00","Height":2,"Final":0}”
//After Changes in the Model I am getting it in the required Array format:
//{"No":null,"Desc":"asfasfasfasfasfasfasfasfasfasfasfasf","Date":"2013-03-27T00:00:00","Height":0,"Final":null}
//{"No":null,"Desc":"etwetwetwetwet","Date":"2013-03-27T00:00:00","Height":0,"Final":0}
//{"No":null,"Des...
return Json(jsnRslt, JsonRequestBehavior.AllowGet);
}
In View:
<div>
<script type="text/javascript">
$(document).ready(function () {
$("#grid").kendoGrid({
dataSource: {
type: "json",
serverPaging: true,
pageSize: 5,
groupable: true,
selectable: "row",
transport: { read: { url: "Records", dataType: "json"} }
},
height: 400,
scrollable: true,
sortable: true,
filterable: true,
pageable: true,
columns: [
{ field: "No", title: " No" },
{ field: "Desc", title: "Description" },
{ field: "Date", title: "Date" },
{ field: "Height", title: "Height" },
{ field: "Final", title: "Final" }
],
dataBound: function () {
this.expandRow(this.tbody.find("tr.k-master-row").first());
}
});
});
</script>
</div>
But after all this all I can see is an empty grid. And no errors in JavaScript console.
Please help
The JSON that you return from the server should be array. You currently it seems that you are returning single objects with multiple fields that are the same.
Here is an example how the JSON should look like:
[{"No":null,"Desc":"asfasfasfasfasfasfasfasfasfasfasfasf","Date":"2013-03-27T00:00:00","Height":0,"Final":null},
{"No":null,"Desc":"etwetwetwetwet","Date":"2013-03-27T00:00:00","Height":0,"Final":0},
{"No":null,"Desc":"asfasfasfskfjklajsfkjasklfjklasjfklajsfkljaklsfjklasjfkljasfkljlasf","Date":"2013-03-27T00:00:00","Height":0,"Final":0}]
I think following code will be useful for you and let me know if you have any problem:
$('#gridName').kendoGrid({
dataSource: {
type: "odata",
transport: {
read: {
contentType: "application/json; charset=utf-8",
type: "POST",
url: 'YourURL'
}
},
pageSize: 10,
type: "json"
},
scrollable: true,
sortable: true,
resizable: true
});
Inside you dataSource set data.
data: #Html.Raw(Json.Encode(Model.RemoteObject)),
RemoteObject is you object containing all data.
First I check your tranport read URL. have you trace the controller if it fires the GetRecords command?
transport:
{
read: {
//if you don't use area then remove it
url: "#Url.Action("GetRecords", new { area = "YourAreaName", controller = "YourControllerName" })",
dataType: "json"
}
}
if it still doesn't fix your problem, then modify your Controller,
public ActionResult GetRecords([DataSourceRequest] DataSourceRequest request)
{
var usrObj = new User();
var jsnRslt = usrObj.GetResult(Session["Id"].ToString());
return Json(jsnRslt.ToDataSourceResult(request), JsonRequestBehavior.AllowGet);
}
here's the link to understand the Kendo's ToDataSourceResult

Resources