I'm using a JqGrid in multiselect mode and recover the user's selection. The JqGrid is defined as follow :
$("#StatusList").jqGrid({
url: '#Url.Action("UpdateStatusList", "Inventory")',
datatype: 'json',
mtype: 'GET',
colNames: ['Status', 'statusId'],
colModel: [
{ name: 'Status', index: 'Status', align: 'left', sortable: false },
{ name: 'statusId', index: 'statusId', hidden: true}]
});
I don't have any issue for all the communication between the server and the client. Everything works fine. But I feel like I am duplicating data when filling the JqGrid with this function that sends the JSON data :
public ActionResult UpdateStatusList()
{
var jsonData = new
{
rows = (from status in DatabaseInMemory.WoodStatus.GetEntities()
select new
{
i = status.ID,
cell = new string[] { status.Name,
status.ID.ToString() }
}).ToArray()
};
return Json(jsonData, JsonRequestBehavior.AllowGet);
}
As you can see the id is passed two times :
- for the JSON Id.
- for the hidden column that helps me recover the id from the grid.
Back to the client, the JSON Id is not hold in the selarrrow property. This property holds ids based on position in the grid. I'm using it to get the selected data, and recover the real ids.
Is JqGrid processes and hold the id passed through JSON data, or is it lost and an hidden column is always needed to keep track of the rows?
You should change i = status.ID to id = status.ID.
Related
The situation is follow: we have a kendo grid with columns, in one column we have a kendo dropdown for filtering purposes. Client side based on angularjs, server side on c#. So, is it possible to set default value for kendo dropdown without knowing it's id? I'm searching the second day and cant find anything in web/teletrik documentation.
Code
$scope.GridOptions =
{
pageable: { refresh: true, pageSizes: true },
columns: [
// other columns here
{
field: "RegistrationStatus", title: "Status", width: 13,
filterable: {
operators: {
string: {
eq: "Is equal to",
neq: "Is not equal to"
}
},
ui: function(element) {
element.kendoDropDownList({
dataSource: [
{ Name: "Registered", Value: "PassedInterview" },
{ Name: "Pending", Value: "PassedInterview" },
{ Name: "Rejected", Value: "Rejected" }
],
dataTextField: "Name",
dataValueField: "Value",
optionLabel: "--Select Status--"
defaultValue: "PassedInterview" // smth like this, is this possible? or achieve in any other methods instead of taking dropdown id, which I dont know because this is hided inside
});
}
}
}
],
sortable: true,
filterable: true,
selectable: 'row',
editable: 'inline'
};
I made it to work setting the value after its initialization:
element.data("kendoDropDownList").value("PassedInterview");
Demo. Note that you can also use select() method if you like.
The problem is, idk why but you can't call it right after the widget creation, you have to use window.setTimeout(). I know, its ugly. But somewhere between the creation and the showing proccess your function is somewhat ignored and doesn't works if called directly. That is why the timer(try w/o it and check it out by yourself).
I have also tried to set value and index in the creation params, but none worked(they actually should).
I am running into some trouble with my ajax call. Here is the controller code:
[Route("RatingInfo/HandleRequest")]
[HttpPost]
public ActionResult HandleRequest(Dictionary<string, string> textBoxValues)
{
var result = CreateJson(textBoxValues); // This is a simplified example
return Json(result);
}
And here is my Jquery/ajax (Razor syntax):
function PassData () {
var data = {};
$('.divCell input').each(function (index, item) {
var id = $(item).attr('id');
var value = item.value;
data['dictionary[' + index + '].Key'] = id;
data['dictionary[' + index + '].Value'] = value;
});
$.ajax({
url: '#Url.Action("HandleRequest")',
type: 'POST',
dataType: 'JSON',
traditional: true,
data: data,
sucesss: function (result) {
alert('Success');
}
})
}
The idea here is to get the data from each textbox and pass it back to the server as a Dictionary with the id as the key and value as, well, the value.
Stepping through the Chrome debugger, the JS data object is built successfully.
From the debugger:
Local
data: Object
dictionary[0].Key: "Address"
dictionary[0].Value: "123 Main St"
dictionary[1].Key: "ZipCode"
dictionary[1].Value: "99999"
dictionary[2].Key: "Phone1"
dictionary[2].Value: "(555) 555-5555"
...
__proto__: Object
However, when the data is passed back to the controller, the values inside textBoxValues does not contain the passed data. Rather, it contains two key/value pairs with keys controller and action and values the names of the controller and action.
From the Visual Studio debugger:
textBoxValues = Count = 2
[0] = {[controller, RatingInfo]}
[1] = {[action, HandleRequest]}
How can I get Jquery to pass the data rather than the controller/action names? I am confused as to how this can even happen in the first place. Any help would be appreciated.
UPDATE
Sorry, I had put wrong code in.
The reason why this was not working is because the name of the parameter was incorrect, giving you a mismatch.
The below will work for you. Notice the name of dictionary is changed to your parameter textBoxValues:
function PassData() {
var data = {};
$('.divCell input').each(function (index, item) {
var id = $(item).attr('id');
var value = item.value;
data['textBoxValues[' + index + '].Key'] = id;
data['textBoxValues[' + index + '].Value'] = value;
});
$.ajax({
url: '#Url.Action("HandleRequest")',
type: 'POST',
traditional: true,
data: data,
sucesss: function (result) {
alert('Success');
}
})
}
I am not too familiar with javascript, so I need help here. I have this method which returns a list of Customers (2000+), so the Select2 dropdown hangs. I want to enable paging, but I am not sure what I need to change. Here is my javascript code:
var GetCutomerDDL = function(cient) {
var Json = {},
customers = [];
$ddlCustomers.select2('val', '');
Json.client = cient;
$.post(urlContent + 'Cutomer/GetCustomerDDL', Json, function(data) {
}, 'json').done(function(data) {
customers = data;
$ddlCustomers.select2({
placeholder: "Select Customer(s)",
allowClear: true,
multiple: true,
data: customers
});
});
};
GetCustomerDDL uses LINQ to just return all the customers, but I want to enable paging so don't load over 2000 records in a dropdown at once. What do I need to change in the javascript and the server side?
The Select2 control includes "infinite scrolling". That may be what you're looking for.
Scroll2's main page is found here: http://select2.github.io/
On the server-side, you'll want to use Skip() and Take() LINQ operators to skip forward in the data and to take only a certain number of items from your data. Select2 should pass which items to skip and take to your controller.
Edit:
Try changing this:
$.post(urlContent + 'Cutomer/GetCustomerDDL', Json, function(data) {
}, 'json').done(function(data) {
customers = data;
$ddlCustomers.select2({
placeholder: "Select Customer(s)",
allowClear: true,
multiple: true,
data: customers
});
});
to this:
$ddlCustomers.select2({
ajax: {
url: urlContent + 'Cutomer/GetCustomerDDL',
dataType: 'json',
data: function (term, page) {
return {
q: term, // search term
pageLimit: 10,
page: page, // page number
client: client
};
},
results: function (data, page) {
var more = (page * 10) < data.total; // whether or not there are more results available
return { results: data.customers, more: more };
}
},
});
On your controller, you'll want to return your sub-list of customers in a "customers" property, and the total customers in a "total" property.
return Json(new { customers = customers.Skip(...).Take(...),
total = customers.Count() }, JsonRequestBehavior.AllowGet);
Sample json result:
{ customers: [...], total: 2000 }
Im asp.net mvc3 c# code returns json list like this:
return Json(new { name = UserNames, imageUrl = ImageUrls });
UserNames and ImageUrls are both List<string> types
And this is my javascript
function StartSearch(text) {
$.ajax({
url: '/Shared/Search',
type: 'POST',
data: { SearchText: text },
dataType: 'json',
success: function (result) {
$.each(result, function (i, item) {
alert(result[i].name);
});
}
});
}
How I can get names and ImageUrls?
Thanks
Access name as a property of result like this result.name[i]
Essentially, result will contain name and imageUrl which are both arrays, just like you have defined in your anonymous type, so your code should be modified like this to display an alert for each name in the name array
function StartSearch(text) {
$.ajax({
url: '/Shared/Search',
type: 'POST',
data: { SearchText: text },
dataType: 'json',
success: function (result) {
$.each(result.name, function (i, item) {
alert(item);
});
}
});
}
as $each iterates over the items in the name array, it will pass the item to the second parameter of your call back, i.e. item.
so
$.each(result.name, function (i, item) {
alert(item);
});
will popup each name.
Notes:
You may want to change the properties on your anonymous type to reflect that they are a collection:
return Json(new { UserNames = UserNames, ImageUrls = ImageUrls });
this way it will make more sense when you iterate over them in your success function.
As AlfalfaStrange pointed out, I didn't demonstrate how you might access both arrays. Which made me think, what is the relationship between user names and image urls?
Is this a list of images for a user? Maybe what you should consider is creating a specific model for this. For instance, UserDisplayModel:
public class UserDisplayModel
{
public string UserName {get;set;}
public string ImageUrl {get;set;}
}
In your controller return a list of UserDisplayModels. If this is the case, you'll have to rethink why they are two separate lists in the first place. Maybe ImageUrl should be a field on the User table.
So now, when you're returning a single list, e.g.
List<UserDisplayModel> users = //get users from db
return Json(new { Users = Users});
you can iterate them in one go in js code:
$.each(result.Users, function (i, item) {
alert(item.Name);
alert(item.ImageUrl);
});
This alerts the value of Name from each record of each list.
$.each(result, function (i, item) {
for (var x = 0; x < result.FirstList.length; x++) {
alert(result.FirstList[x].Name);
alert(result.SecondList[x].Name);
}
});
This assumes your Json response if formed correctly. Like this:
return Json(new { FirstList = results, SecondList = otherResults }, JsonRequestBehavior.AllowGet);
But as a side note, I see other problems with your code that you need to address
You're actually not performing a POST, you're searching based on input. Change POST to GET in your Ajax call
Change your action return line to allow for the get and make sure your are returning a JsonResult.
Naming conventions for C# method parameters call for Pascal-casing. Use a lowercase letter for first character
public JsonResult Search(string searchText) {
....
return Json(new { name = UserNames, imageUrl = ImageUrls }, JsonRequestBehavior.AllowGet);
}
I am trying, and struggling, to send an array via JSON to a MVC controller action.
Here is what I have and what i've tried...
//Get checked records
var $checkedRecords = $(':checked'); //e.g. 3 rows selected = [input 4, input 5, input 6]
//Have tried following:
sendingVar: $checkedRecords.serializeArray(); // gives array of 0's
sendingVar: JSON.stringify($checkedRecords); // gives "{\"length\":1,\"prevObject\":{\"0\":{\"jQuery1313717591466\":1,\"jQuery1313717591653\":13},\"context\":{\"jQuery1313717591466\":1,\"jQuery1313717591653\":13},\"length\":1},\"context\":{\"jQuery1313717591466\":1,\"jQuery1313717591653\":13},\"selector\":\":checked\",\"0\":{}}"...wtf
//Post
$.post(url, { sendingVar: sendingVar }, function(data) {alert(data); });
How do I do it ?
edit: to those that suggest sending $checkedRecords "as is" from the top line - that is not working. I get a strange exception somewhere in the jquery framework :(
uncaught exception: [Exception... "Could not convert JavaScript argument" nsresult: "0x80570009 (NS_ERROR_XPC_BAD_CONVERT_JS)" location: "JS frame :: http://.../.../.../jquery-1.4.4.min.js :: <TOP_LEVEL> :: line 141" data: no]
which I think means it is attempting to assign null to something it cannot.
Edit: i'm using MVC2 not 3
Edit2: After #Monday's answer- the problem is due to how I have built the array like [input 4, input 5, input 6] and not [4,5,6] - any ideas how I can just get the values in the array instead ?
Edit3: Stop voting up duplicate when it's not. Did you actually read my problem or read the problems linked? this is a different issue
#Daveo:
I don't want to build in an overriding custom attribute just to send an array from JSON, that is rediculous as we've already covered in this question-it is not necessary.
MVC3 - irrelevant
Here is my demo,use mvc2,hope some helps~
The key to success is traditional
set the traditional parameter to true
$(function(){
var a = [1, 2];
$.ajax({
type: "POST",
url: "<%= ResolveUrl("~/Home/PostArray/") %>",
data: {orderedIds: a},
dataType: "json",
traditional: true,
success: function(msg){alert(msg)}
});
})
Since jquery 1.4 this parameter exists because the mechanism to serialize objects into query parameters has changed.
and action is~
[HttpPost]
public ActionResult PostArray(int[] orderedIds)
{
return Content(orderedIds.Length.ToString());
}
you can also use JSON.stringyfy to sent the data as a string then use JavaScriptSerializer class to retrive the data.
In C# code, to get the data, will look like this:
JavaScriptSerializer js = new JavaScriptSerializer();
js.Deserialize<T>(string paramiter);
use this simple code
var url = '/sampleController/sampleAction'
var params = {sendingVar: [1,2]}
$.post(url, params , function (data) {
$("#lblResult").html(' : ' + data);
}).fail(function (e) {
alert(e);
});