ASP MVC WEB Api JS table - jqgrid

Can anyone point me in the right direction?
I'm looking to use DataTables.net or jqGrid with an ASP MVC4 ApiController action for the source.
The problem I have is that i just return an array of objects..
e.g.
[{"Name":"Brian", "Age" : "35"}, {"Name":"Jim", "Age" : "45"}]
I don't format it like the samples i.e. with aaData or arrays of string.
Can anyone tell me how they overcome this problem?
I'll even settle for jqGrid if someone and point me in the direction of a good example.
tnx
Brian.

It' not a problem in jqGrid. You need just define jsonReader which describe how the data can be read by jqGrid. For example
See the demo:
It uses
jsonReader: {
repeatitems: false,
id: "Name",
root: function (obj) {
return obj;
}
}
and the JSON data which you posted.

To use different actions(Post, Put and Delete) of ASP.NET Web API for add edit delete operations, check following example:
http://techbrij.com/1017/add-edit-delete-jqgrid-asp-net-web-api

Related

JQGrid local search multiple columns

I'm using JQGrid with local search (inside the columns header).
I have 2 columns that I want to merge the search for them -
so, when I write a value inside the search input this value will be searched in 2 columns at the same time.
Is it possible to implement this? and if so, HOW ??
Thank's In Advance.
If I understand your question correctly you use filterToolbar for searching in a grid which has datatype: "local". In the case jqGrid fills postData.filters parameter in the form described here, which corresponds searching via dialog with multipleSearch: true.
You can implement your requirements inside of beforeSearch callback of filterToolbar method. Inside of the callback you can use
var postData = $(this).jqGrid("getGridParam", "postData");
to get the reference on postData object. Then you can use JSON.parse(postData.filters) to convert filter created by filterToolbar to object. It will be object like
{
"groupOp": "AND",
"rules": [{
"field": "someColumnName",
"op": "cn",
"data": "data entered by user"
}]
}
You can modify the object by adding one more item in "rules" and setting postData.filters to new value JSON.stringify(modifiedFiltersObject). Finally beforeSearch callback should return false to continue filtering. In the way, you will be able implement your requirements.
If you use Guriddo jqGrid, you can use filterInput method. This method allow to search on all fields in grid data using single input value. Here is description of the method
Here is a demo

Button in jqgrid

I have been using ng-grid for displaying data and now migrating to jqgrid. I'm a newbie to this tech and I have tried creating a button which performs some other action like validating and opening a new form. I could invoke my Angular JS variable in that button. Can someone help me?
function ActionitmGridformatter(cellvalue, options, rowObject) {
var itmgrid= "";
return itmgrid;
}
$scope.itmgrid= function(row){
alert("hii");
...
};
Also the above itmgrid variable is inside the controller. Can someone post useful links for jqgrid docs and any other inputs will be helpful for me. Kindly ignore if the question is repeated and also share the relevant link.
Thanks
I recently needed to do the same thing, I had a grid of ordered products and I needed to create a link in each row that pertained to that order, here is how I went about that:
Create a function:
function orderLinkFormatter (cellvalue, options, rowObject) {
var base = window.location.origin;
return '' + rowObject.OrderNumber + '';
}
In your grid change you colModel to look like this:
{ name: 'OrderId', index: 'OrderId', width: 100, search: false, formatter:orderLinkFormatter, align: 'center'},
You will end up with something like in this DEMO.
Or this DEMO
I would also suggest that you try using free-jqgrid, it is a free fork of jqgrid that is updated almost daily and the author: Oleg provides really good support on this site.

Dojo.query foreach accessing element value

I'm a newbie in Dojo framework, so I hope my question is not really dumb.
I have a link in my web page :
Delete
The variable "index" is well defined, no issue with that.
Then, I've written this piece of code to add an action to the onclick event on my link and a JS function to call before the submit :
dojo.query("a[name=supprimerEnfant_name]").forEach(function(element) {
Spring.addDecoration(new Spring.AjaxEventDecoration({
formId: "form_id",
elementId: element.id,
event: "onclick",
beforeSubmit: function(){
jsFunctionToCall(element.value);
},
params: { _eventId: "deleteEvent", fragments:"frag"}
}))
});
In my jsFunctionToCall, I can get the element.id (checked and it's OK) but the element's value is null and I can't figure out why.
I'm probably missing something important, could you help me with that ?
Thanks in advance.
You should be aware that element.value only works with elements where it's part of the DOM, defined by W3C. So, if you look at the HTMLInputElement interface (used by form elements), you will see that it clearly has a property called value, referencing to the the value of the element.
However, the same is not true for an HTMLAnchorElement. This means the proper way to retrieve the value of the value attribute, is by selecting the attribute itself, using the getAttribute() function or by using the the dojo/dom-attr Dojo module.
For example:
require(["dojo/query", "dojo/dom-attr", "dojo/domReady!"], function(query, domAttr) {
query("a").forEach(function(element) {
console.log(element.id);
console.log(domAttr.get(element, "value")); // This will work
});
});
Demonstration: JSFiddle
The dojo query will return the domNode references always. Anyhow, the anchor element is a HTML element. So, this is nothing to do with Dojo and lets see whats wrong with the JS part.
The "value" is not a standard attribute of anchor element. So, the additional attributes need to be accessed using "getAttribute" method.
i.e. in your case,
element.getAttribute('value')

jqGrid 4.2 Custom search with non-grid fields

I'm using jqGrid 4.2 with the filterToolbar, which works great. I'd like to add some type of custom search to query (server-side) fields that are not part of the colModel.
Prior to 4.0 I would have used filterGrid along the lines of this:
$('#keyword').jqGrid('filterGrid', '#ticket-grid',
{
gridModel: false,
filterModel: [
{ label: 'Keyword', name: 'keyword', stype: 'text'},
{ label: 'Inclued Closed?',name : 'includeClosed', stype: 'checkbox'}
]
});
I understand that this is no longer supported, and an stype: 'checkbox' doesn't work anyway.
How do I do this with the new search module/mechanism?
If I understand you correct you have already on the page, for example above the grid, some controls (text input, selects, chechboxes) which allow the user to define additional criteria of the results which the user want see in the grid. In the case you can use postData with methods (functions) in the way described in the old answer.
If any kind of grid refreshing: request to filter the data from the searching toolbar, changing of the page or the page size, changing of sorting and so on will always follow to the Ajax request to the server. In the case the properties from postData option of jqGrid will be added like other standard parameters (sidx, sord, page, ...). If one from the properties of the postData is defined as function (if a method of postData) then the function will be called to construct the parameter which will be sent to the server. So the current information from you custom searching controls (text input, selects, chechboxes) will be send to the server. In the way you need only use the parameters on the backend to filter the results.
So you have to define fields yourself. For example the text input with id="keyword-input" and checkbos with id="includeClosed" and then use postData in about the following form:
$('#keyword').jqGrid(
// ... other jqGrid options
postData: {
keyword: function () { return $('#keyword-input').val(); },
includeClosed: function () { return $('#includeClosed')is(':checked'); },
}
});

How to change WebGrid action for getting data (.NET MVC3)

I have a Partial View that renders WebGrid. My controller looks like
public ActionResult Index()
{
return View();
}
public ActionResult GetUserList(int? page, string sort, string sortdir)
{
var model = UserModel.getList(page,sort,sortdir);
return PartialView("_UserList",model);
}
Index.cshtml :
....
#Html.Action("GetUserList")
The problem is that every time I click on grid navigation or sort links it calls Index method. How can I make Webgrid to execute a different action (GetUserList in this case)? I'm sure I can prepend GetUserList to all links in grid using jquery, but I believe it should be a better way.
It's also possible that what I'm doing is completely wrong, so thanks for your suggestions.
After lot of monkeying around and digging (and even fiddling with Reflector with WebGrid's source code), I came to the conclusion that with WebGrid, you cannot control/change the Header link action.
To create the header link URL, the path is taken from HttpContext.Request.Path, so there is no way to customize it to point to a different route.
One very ugly hack would be to tap into to jQuery Ajax's events (since the header link uses jQuery.load to sort) and overwrite the URL:
Album Id
Better solution would be to use:
Telerik Grid which lets you specify custom routes and also offers much more flexibility in rendering your layout
or MvcContrib Grid (not sure if this lets you modify header links but definitely offers more flexibility than WebGrid)
#MrChief had the idea above about the ugly hack...I put that together. Here is the main code that I used to do this. It does, indeed, hijack the ajax call before it is put on the wire. The key is to modify the URL that is getting sent because the grid will grab that URL from HttpContext.Request.Path. and plug it into the onclick for the anchor element.
I put this into my main common.js and will simply attach a function to capture the ajaxSend event which happens just before the data is sent.
// Used to hijack the sending of all AJAX calls. Before it sends the call to the server, it checks to see if the
// active element (the element that prompted the call) is marked with a given class. If so, then it will perform
// the given operation.
$(document).ajaxSend(function (event, jqXHR, ajaxOptions) {
var activeElement = document.activeElement;
if ($(activeElement).attr('redosorturl') != null) {
// If this is a sort anchor link from a grid that needs to have the sort link redone, do it here.
// the code is in the eipGrip.js file.
if ($(activeElement).attr('redosorturl').toString() == 'redoSortURL') {
var newURL = RedoGridSortURL(activeElement, ajaxOptions.url.toString());
ajaxOptions.url = newURL.toString();
}
}
return false;
});
When rendering the page, I have marked the tag in column header that contains the incorrect URL with a class named "redosorturl', so I know when I hijack the ajax call, the operation has to be done on this element. I then call a custom function that gives me the correct URL, then the ajaxOptions.url is then rewritten with that new URL.
I have to pass the activeElement to that rewrite function so I can traverse up the DOM to get the grid information, where I have put data like the controller and action method that is used along with and IDs and other info that I use for the URL. Likewise, I pass in the current url string because the grid will inject a token at the end of the url that I parse off and put on the new url.
Your conclusion isn't right. You just need to wrap your webgrid in a Get form:
using (Html.BeginForm("GetUserList", "ThingaMaBob", System.Web.Mvc.FormMethod.Get))
{
var grid = new WebGrid(
...
));
Html.Hidden(grid.SortFieldName, grid.SortColumn);
Html.Hidden(grid.SortDirectionFieldName, grid.SortDirection == SortDirection.Ascending ? "ASC" : "DESC");
}
The hiddens are so that the sort dir and sort field end up in parseable form in the querystring. You end up with urls like localhost/ThingaMaBob/GetUserList?someotherfields=whatever=&sort=city&sortdir=ASC
If you remove [HttpPost] attribute and let the route come to the same function. you'll find the Request["page"] value in your method. this will allow you to put a check on Request["Page"] value.

Resources