How to populate jqgrid using asp.net mvc 3 - c#

I'm trying to populate a jqgrid using data from my [HttPost] controller method.
my controllers look like this
Public ActionResult Index()
{
SearchModel sm = new SearchModel();
// gets specific data from sm here
return View(sm);
}
[HttpPost]
Public ActionResult Index(SearchModel sm)
{
// does some stuff with the entered data from the form to return search results
// not sure what exactly to do here....
}
My form looks like this:
#model SearchModel
#{
//layout stuff and other script links are here
}
{Html.EnableClientValidation();}
#using (Html.BeginForm("Index", "Page",
FormMethod.Post, new { id = "search-form" }))
{
//I have the form and post data here
}
#if (Model.SearchRecords != null)
{
Html.RenderPartial("SearchRecordsPartial");
}
My Partial where the jqgrid is looks like this:
#model SearchModel
<div>
<table id="list" class="scroll" cellpadding="0" cellspacing="0"></table>
<div id="pager" class="scroll" style="text-align:center;"></div>
</div>
The jquery:
$(function () {
$("#list").jqGrid({
url: '/Page/Index/',
datatype: 'json',
mtype: 'GET',
colNames: ['Id', 'Votes', 'Title'],
colModel: [
{ name: 'Id', index: 'Id', width: 40, align: 'left' },
{ name: 'Votes', index: 'Votes', width: 40, align: 'left' },
{ name: 'Title', index: 'Title', width: 400, align: 'left'}],
pager: jQuery('#pager'),
rowNum: 10,
rowList: [5, 10, 20, 50],
sortname: 'Id',
sortorder: "desc",
viewrecords: true,
imgpath: '/content/themes/ui-lightness/images',
caption: 'Appeal Case Records'
});
});
Any help or links to how to do this would be awesome. I've tried searching online for helps and there is a lot of different articles but I can't seem to find one that uses asp.net mvc with populating a jqgrid from form data.
Thanks,

Here's a good link:
Using jQuery Grid With ASP.NET MVC
I'm putting together an MVC4 jqGrid, and this helped me out quite a bit.
EDIT:
Just to add a bit more color, I don't think you want to return your grid results in your Index action. jQgrid is going to call the url you specify whenever it needs to load new data - as a result of sorting, searching, refreshing, etc... If you take a look at the article I linked, it goes into this in some more detail.

If you just want to show data in grid, you can use below code, but if you want to use the functionality like add, edit, delete, filter, sort,etc this code is not enough, please specify the requirments in details.
[HttpPost]
Public ActionResult Index(SearchModel sm)
{
List<Object> returnData = new List<Object>();
returnData.Add(new { id = 1, cell = new string[] {"Id1","Votes1","Title1"} });
returnData.Add(new { id = 2, cell = new string[] {"Id2","Votes2","Title2"} });
returnData.Add(new { id = 3, cell = new string[] {"Id3","Votes3","Title3"} });
var result = new { total = 1, page = 1, records = 3, rows = returnData };
return Json(result, JsonRequestBehavior.AllowGet);
}

You should pass the sorting and paging parameters in that controller action
[HttpPost]
public ActionResult ListCustomer(string sidx, string sord, int page, int rows)
{
// return the json data
}

Related

jQuery DataTable Column RenderLinkAsButton in C# ASP.NET MVC Project?

I am replacing a jQuery DataTable that performs client side processing. I would like to add a Details column, such as the following:
When one of the Details buttons is clicked, the Details View for that particular record is opened.
The following is the code that used to accomplish this:
<td class="action-button-column">#Html.RenderLinkAsButton(ButtonTypes.View, Url.Action("Details", "Controller", new {id = model.Id, area = "Area"}), Enums.ButtonSize.Small)</td>
Can I use/add RenderLinkAsButton in a DataTable column?
I know that I can use the following code to create a button that will perform the same thing:
columns: [
{
data: "Id",
title: "Details",
render: function (data) {
var myUrl = '#Url.Action("Details", "Controller")?Id=' + data;
return '';
}
}
]
However, I would like to include the icon, in this case an opened folder, to be consistent with other Index Views that use client side processing DataTables.
I just had to add the following with a leading space: fa-folder-open
columns: [
{
data: "Id",
title: "Details",
render: function (data) {
var myUrl = '#Url.Action("Details", "Controller")?Id=' + data;
return '';
}
}
]

JTable Not Showing Sort Or Pagination

I am passing in a JSON array to my JTable and am trying to use AJAX to show the data with no page load. This is an asp.net core mvc app with a C# back-end. The data loads, but as i said i do not have the ability to sort and all results are shown instead of only 10 per page as I request in the sorting param.
What do I ned to change here?
[Route("api/ca")]
public JsonResult Index()
{
var ListData = _context.CIModel.FromSql("StoredProcedureName").ToList();
return Json(new { Result = "OK", Records = ListData, TotalRecordCount = ListData.Count });
}
$('#btnTest').click(function () {
$('#jTableTest').jtable({
paging: true,
pageSize: '10',
sorting: true,
defaultSorting: 'Name ASC',
actions: {
listAction: function (postData, jtParams) {
return $.Deferred(function ($dfd) {
$.ajax({
url: 'https://localhost:44328/api/ca?jtStartIndex=' + jtParams.jtStartIndex + '&jtPageSize=' + jtParams.jtPageSize + '&jtSorting=' + jtParams.jtSorting,
type: 'GET',
dataType: 'json',
success: function (data) {
$dfd.resolve({ Records: data.records, Result: data.result, TotalRecordCount: data.TotalRecordCount });
},
error: function () {
$dfd.reject();
}
});
});
}
},
fields: {
name: {
title: 'Name',
width: '35%'
},
phone: {
title: 'Phone',
width: '15%'
},
yrsexp: {
title: 'Experience',
width: '15%'
}
}
});
$('#jTableTest').jtable('load');
});
Sorting and paging are both SERVER side operations. You need slight changes on both client and server.
On the client, in this example you don't need to write your own deferred function, Just give jTable the URL. It will then pass, paging (jtStartIndex and jtPageSize) and sorting (jtSorting) parameters to the server. These parameters are in the jtParams argument passed to the deferred function, so you have to forward them in you ajax call.
One the server, you need to respond to these sorting and paging parameters. Do note, that on a paged reply, TotalRecordCount is the total number of unpaged records. not the number returned. It is used by jTable to show the total number of pages.

Using variable from a C# class in a Javascript code with Razor

I'm developing a web application with Telerik Kendo in Razor. Here is my problem:
I have a variable that I set as a type List<class>.
#{
ViewBag.Title = "Home Page";
var dpdminst = new DB();
var data = dpdminst.getdata();}
I want to be able to use this variable (data) to set my DataSource in my Javascript:
<script>
var displaydata = #data
$(document).ready(function () {
$("#grid").kendoGrid({
height: 550,
groupable: true,
sortable: true,
pageable: {
refresh: true,
pageSizes: true,
buttonCount: 5
},
dataSource: {
data:displaydata,
schema: {
model: {
fields: {
amount: { type: "string" },
}
}
},
columns:["amount"]
}
});
});
</script>
Does anyone know if this can be done?
Here is my JsonResult:
public JsonResult GetJsonData()
{
var DBinst = new DB();
var TradeData = DBinst.tradedata();
var json = JsonConvert.SerializeObject(TradeData);
var result = new JsonResult()
{
Data = json
};
return result;
}
Have an action method which returns the data you want in JSON format. in your document.ready event, make an ajax call to get this data and then you can set it as your data source.
public ActionResult GetJsonData()
{
var dpdminst = new DB();
var data = dpdminst.getdata();
return Json(data,JsonRequestBehaviour.AllowGet);
}
and in your view use the getJSON method to get data from this action method and use that as needed. You may format the incoming json as per your UI requirements
$(document).ready(function () {
$.getJSON("#Url.Action("GetJsonData","YourControllerName")",function(data){
// you have your json data in the "data" variable.
// now you may use it to set the data source of your grid library
});
});
If you dont want to deal with ajax/json, then I would try to achieve what you want as follows:
<script>
var displaydata = [
#foreach (var record in dpdminst.getdata())
{
#: { amount: '#record' },
}
];
$(document).ready(function () {
$("#grid").kendoGrid({
height: 550,
groupable: true,
sortable: true,
pageable: {
refresh: true,
pageSizes: true,
buttonCount: 5
},
dataSource: {
data:displaydata,
schema: {
model: {
fields: {
amount: { type: "string" },
}
}
},
},
columns:["amount"]
});
});
</script>
Also please notice that you had columns:["amount"] in a wrong place, also this code has to be in your cshtml for razor syntax to work properly.

Why is my Kendo AutoComplete widget not binding to a JSON object?

I have the following code in an MVC controller:
public JsonResult ARequest()
{
Dictionary<string, object> AnObject = new Dictionary<string,object>();
AnObject["foo"] = new object[] {"item 1", "item 2", "item 3"};
return Json(AnObject, JsonRequestBehavior.AllowGet);
}
And it works as expected; when I call it from a browser, I get the following JSON object:
{"foo":["item 1","item 2","item 3"]}
I have another file, this time with a Kendo UI Autocomplete Widget. Here is the code:
<input id="products" style="width: 250px" />
/*...*/
$("#products").kendoAutoComplete({
filter: "contains",
minLength: 3,
dataTextField: foo,
dataSource: {
type: "odata",
pageSize: 10,
transport: {
read: {
url: "education-portal/ARequest"
}
}
}
});
As per the official examples here and here.
The problem is, when I load the page I don't get anything. The AutoComplete is blank and it stays blank. No results show up when I type anything in the box. Any idea what went wrong? I can't see it for the life of me.
There are several problems:
You should not define dataTextField since your array of value are not objects but strings.
You should say where in the received data is actually the array of items.
Is the type odata or JSON?
It should be something like:
$("#products").kendoAutoComplete({
filter: "contains",
minLength: 3,
dataSource: {
type: "json",
pageSize: 10,
transport: {
read: {
url: "education-portal/ARequest"
},
schema : {
data: "foo"
}
}
}
});
Example here : http://jsfiddle.net/OnaBai/rSjpS/
Since you are wrapping the collection inside a field called foo, you should specify this via the dataSource.schema.data options.
e.g.
dataSource: {
schema: {
data: "foo"
}
}
You do not have to specify any datavaluefield or datatextfield

How to do external filtering on jqgrid

I am implementing jqGrid in my ASP.net web aplication, and I don't want to use the inbuilt filtering provided by jqGrid. So, I thought of using external filtering.
I will have a textbox. As soon as a user enters a value and clicks on the button filter, I would like to reload the grid. I am using server side pagination and I must do server side filtering.
I have some posts regarding this, but I was not able to find a solid example to demonstrate this.
I also dont know how the filter value is recieved in the C# code to do the filtering.
You can do it with postData parameter in jQGrid and pass your own values to filter and refresh grid
$(document).ready(SearchPatients);
and
function SearchPatients() {
'use strict';
jQuery("#patient-search-grid").jqGrid({
url: '/Patient/Search/',
datatype: 'json',
mtype: 'POST',
postData: { ID:function(){return $("#txtbkgID").val();} },
//postData:{search:function () { return getSearchPostData() } },
colNames: [{'Id','Pid','FullName'}],
colModel: [
{ name: 'Id', index: 'Id',hidden: true },
{ name: 'PatientIdentifier',index: 'PatientIdentifier'},
{ name: 'FullName', index: 'FullName'}
],
height: "100%",
pager: '#patient-search-pager',
rowNum: 10,
rowList: [10, 30, 50],
sortname: 'Id',
sortorder: 'desc',
viewrecords: true,
caption: "Search Results"
}
function getSearchPostData(){
var searchData = {};
searchData.PatientIdentifier = $('#patient-identifier').val();
searchData.FirstName = $('#first-name').val();
searchData.LastName = $('#last-name').val();
return JSON.stringify(searchData);
}
In Controller add optional parameter ID
[HttpPost]
public JsonResult Search(string ID)
{
//Request.Params["ID"] also will work
}

Categories

Resources