Devexpress MVC5 Grid GetRowKey(e.visibleIndex) returns always null - asp.net-mvc

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

Related

EF Core BulkInsert 'Object reference not set to an instance of an object.'

My EF Core BulkInsert throws error when inserting more than 80 rows, below is the example insert 80 rows data
Insert 80 rows
but when i try 100rows the error as shown
System.NullReferenceException: 'Object reference not set to an instance of an object.'
Im using JSON for the data
function Save() {
var fail = {
title: 'Data insert fail',
message: 'refresh page to save again',
position: 'topRight'
};
console.log(_oSeismics);
if (_oSeismics.length > 0) {
var ajaxRequest = $.ajax({
url: "../PmepTempAdd/SavePmepVSP/",
type: "POST",
data: { data: _oSeismics },
dataType: "json",
beforeSend: function () {
},
});
ajaxRequest.done(function (data) {
swal('Success!', 'Successfully saved.', 'success');
});
ajaxRequest.fail(function (jqXHR, textStatus) {
iziToast.error(
fail
);
});
}
else {
iziToast.error(
fail
);
}
}
function NewSeismicObj() {
var now = new Date();
var date = now.getFullYear() + '-' + (now.getMonth() + 1) + '-' + now.getDate();
var time = now.getHours() + ":" + now.getMinutes() + ":" + now.getSeconds();
var dateTime = date + ' ' + time;
console.log(dateTime)
var oSeismic = {
No: "",
WellName: "",
SurveyVspYaTdk: "",
VspSonicCalibrationSynthetic: "",
VspReport: "",
VelocityWellCheckshot: "",
WellProgramProposal: "",
FinalWellReportEndOfWellReport: "",
ProcessingDataSgy: "",
RawDataSgy: "",
Recommendation: "",
RowCreated: dateTime
};console.log(dateTime)
return oSeismic;
}
Any Idea whats wrong with this code? for
80 rows runs normal, but over 80 error shown as above
Edit :
I have tried to change parameter into data but still error
PmepTempAddController.cs code
public JsonResult SavePmepVSP(List<VerTempPmepSeismicVsp> data)
{
_VSPt = _db.SavePmepSeismicsVSP(data);
TempData["success"] = "Inserted to TempPmeporary Table successfully";
return Json(_VSP);
}
Service.cs code
public List<VerTempPmepSeismicVsp> SavePmepSeismicsVSP(List<VerTempPmepSeismicVsp> data)
{
_dbContext.BulkInsert(data);
return data;
}
Sometimes Its also depends on which parameter are you using...
var ajaxRequest = $.ajax({
url: "../PmepTempAdd/SavePmepVSP/",
type: "POST",
data: { data: _oSeismics },
dataType: "json",
beforeSend: function () {
},
});
here you have written data: { data: _oSeismics },
So, in the backend, it must have something like the below...
public List<VerTempPmepSeismicVsp> SavePmepVSP( List<VerTempPmepSeismicVsp> data)
Note: Look at the name of parameter.

ajax other parameter is null?

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");
}
});

Difficulty with upload csv to knockout js table (ASP MVC)

I've been working with these two tutorials, but am having difficulty merging them together to get an upload csv to populate the table. It most likely is my lack of understanding of the view model.
Here's the tutorial for the knockout js editable table from the knockout js site: KnockoutJS: Editable Grid Table
And here's the tutorial for uploading a csv I'm referencing:
KnockoutJS - Upload CSV
Here's the javascript code I've been working on to upload a csv to my table. I keep getting "JavaScript runtime error: Unable to get property 'push' of undefined or null reference" - I marked in comments the problem spot. As you can see, I'm having trouble with the view model.
<script>
var UserModel = function (users) {
var self = this;
self.users = ko.observableArray(users);
self.addUser = function () {
self.users.push({
id: "",
firstName: "",
lastName: ""
});
};
self.removeUser = function (user) {
self.users.remove(user);
};
self.save = function (form) {
sendData = ko.toJSON(self.users);
$.ajax({
url: '/Users/CreateMultiple',
contentType: 'application/json',
async: true,
type: 'POST',
dataType: 'json',
data: sendData,
error: function (jqXHR, textStatus, errorThrown) {
console.log("FAIL: " + errorThrown);
},
success: function (data, textStatus, jqXHR) {
console.log("SUCCESS");
}
});
};
};
var viewModel = new UserModel([
{ id: "", firstName: "", lastName: "" }
]);
ko.applyBindings(viewModel);
// Activate jQuery Validation
$("form").validate({ submitHandler: viewModel.save });
/////
/////Upload CSV
/////
$('#lnkUpload').click(function () {
var FileToRead = document.getElementById('UserFile');
if (FileToRead.files.length > 0) {
var reader = new FileReader();
reader.onload = Load_CSVData;
reader.readAsText(FileToRead.files.item(0));
}
});
function Load_CSVData(e) {
CSVLines = e.target.result.split(/\r\n|\n/);
$.each(CSVLines, function (i, item) {
var element = item.split(",");
var csvID = (element[0] == undefined) ? "" : element[0].trim();
var csvFirstName = (element[1] == undefined) ? "" : element[1].trim();
var csvLastName = (element[2] == undefined) ? "" : element[2].trim();
UserModel.users.push(new UserModel()//here's my problem
.id(csvID)
.firstName(csvFirstName)
.lastName(csvLastName)
)
});
}
</script>
I was able to identify the fully qualified for the observable array which in turn made it work:
function Load_CSVData(e) {
CSVLines = e.target.result.split(/\r\n|\n/);
$.each(CSVLines, function (i, item) {
var element = item.split(",");
var csvID = (element[0] == undefined) ? "" : element[0].trim();
var csvFirstName = (element[1] == undefined) ? "" : element[1].trim();
var csvLastName = (element[2] == undefined) ? "" : element[2].trim();
viewModel.users.push({
id: csvID,
firstName: csvFirstName,
lastName: csvLastName
});
}

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.

jquery ajax to bind dropdownlist MVC

I have a 2 dropdownlist, I have to bind the 2nd one based on the Id I got from first dropdown. in the first dropdown I added OnChange event.
function onChange() {
var variantDropDown = $('#VariantName');
$.ajax({
url: '/Admin/CustomProductPinCodesManagement/GetProductVarinats',
type: 'post',
data: { productId: $("#ProductName").data("tDropDownList").value() },
success: function (data) {
$.each(variants, function (i, variant) {
$states.append('<option value="' + variant.Id + '">' + variant.Name + '</option>');
});
},
error: function () {
alert('Error');
}
});
}
and this is the c# code .
[HttpPost]
public ActionResult GetProductVarinats(string productId)
{
var variants = _productService.GetProductVariantsByProductId(Convert.ToInt32(productId));
return Json(new { Result = true, data = variants }, JsonRequestBehavior.AllowGet);
}
but it does not work.
Use val() instead of value()
Change statement
data: { productId: $("#ProductName").data("tDropDownList").value() }
to
data: { productId: $("#ProductName").data("tDropDownList").val() }
and the success should be like
success: function (data) {
//For getting list of variants, you should access it by `data.data.variants`
//because you will get your json object in data, and for getting the value `variants`
//you should capture the `data` property of returned json object like `data.data`
$.each(data.data.variants, function (i, variant) {
$states.append('<option value="' + variant.Id + '">'+ variant.Name + '</option>');
//you can try this also for creating options
//$states.append($('<option/>').text(variant.Name).attr('value',variant.Id));
});
}
so your function should look like :
function onChange() {
var variantDropDown = $('#VariantName');
$.ajax({
url: '/Admin/CustomProductPinCodesManagement/GetProductVarinats',
type : 'post',
data: { productId: $("#ProductName").data("tDropDownList").val() },
success: function (data) {
$.each(data.data.variants, function (i, variant) {
$states.append($('<option/>').text(variant.Name).attr('value',variant.Id));
});
},
error: function () {
alert('Error');
}
});
}
AcidMedia has a library called TTControls which uses Telerik and you can use the TTControls.LinkedDropDown control which solves this problem.

Resources