ASP.net Mvc 2.0 with JQGrid - asp.net-mvc

I have to implement inline editing with combobox in JQGrid,and i have to populate data in combobox from database no hard coded value i have already written the view part and i am using Linq to Sql as model but not able to write controller for that. I have got one sample for that but in sample repository design pattern has been used and i have not to use that.So can any on help me to write thebcontroller part.
My view part is
<%# Page Language="C#" Inherits="System.Web.Mvc.ViewPage<dynamic>" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
<link href="../../Content/jquery-ui-1.10.4.custom.min.css" rel="stylesheet" type="text/css" />
<link href="../../Content/ui.jqgrid.css" rel="stylesheet" type="text/css" />
<script src="../../Scripts/JQGrid/jquery-1.11.0.min.js" type="text/javascript"></script>
<script src="../../Scripts/JQGrid/jquery.jqGrid.min.js" type="text/javascript"></script>
<script src="../../Scripts/JQGrid/jquery.jqGrid.src.js" type="text/javascript"></script>
<script src="../../Scripts/JQGrid/grid.locale-en.js" type="text/javascript"></script>
<script type="text/javascript">
$(document).ready(function () {
$("#Grid").jqGrid(
{ url: '/Default/GetData',
datatype: 'json',
mtype: 'GET',
colNames: ['Id', 'UserName', 'Organization', 'Report Type', 'EmailID', 'Action'],
colModel: [
{ name: 'Id', index: 'Id', align: 'center', width: 30, editable: false },
{ name: 'UserName', index: 'UserName', align: 'center', width: 150, editable: true, edittype: 'select', formatter: 'select', editoptions: { dataUrl: '/Default/UserSelect' } },
{ name: 'Organization', index: 'Organization', align: 'center', width: 200, editable: true, edittype: 'select', formatter: 'select', editoptions: { dataUrl: '/Default/OrganizationSelect' }, editrules: { required: true} },
{ name: 'Report Type', index: 'Report Type', align: 'center', width: 200, editable: true, edittype: 'select', editoptions: { value: 'MN:Monthly; YR:Yearly', defaultValue: 'Montyhly'} },
{ name: 'EmailID', index: 'EmailID', align: 'center', width: 250, editable: true, edittype: 'text', editoptions: { size: 30, maxlength: 40} },
{ name: 'act', width: 100, align: 'center', sortable: false, formatter: 'actions', formatoptions: { keys: true, editbutton: true}}],
pager: jQuery('#pager'),
rowNum: 10,
rowList: [5, 10, 20, 50],
sortname: 'Id',
sortorder: "asc",
viewrecords: true,
caption: 'Regen Users'
});
});
</script>
<title>Index</title>
</head>
<body>
<div>
<table id="Grid">
</table>
</div>
<div id="pager">
</div>
</body>
</html>
And my get data controller is as
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Important.Models;
using System.Linq.Dynamic;
namespace Important.Controllers
{
public class DefaultController : Controller
{
RegenDataContext db = null;
public DefaultController()
{
db = new RegenDataContext();
}
public ActionResult Index()
{
return View();
}
[HttpGet]
public ActionResult GetData(string sidx, string sord, int page, int rows)
{
var pageIndex = Convert.ToInt32(page) - 1;
var pageSize = rows;
var totalRecords = db.rptUsers.Count();
var totalPages = (int)Math.Ceiling(totalRecords / (float)pageSize);
var user = db.rptUsers
.OrderBy(sidx + " " + sord)
.Skip(pageIndex * pageSize)
.Take(pageSize).AsQueryable();
var jsonData = new
{
rows = (
from rptUser u in user
select new
{
i=u.ID,
cell=new string[]{u.ID.ToString(),u.UserName, u.UserOrganizationID.ToString()}
}).ToArray()
};
return Json(jsonData, JsonRequestBehavior.AllowGet);
}
public ActionResult UserSelect()
{
return View();
}
public ActionResult OrganizationSelect()
{
return View();
}
}
}
help me to write controller action for data url UserSelect.

As per below jqGrid documentation
Setting the editoptions dataUrl parameter: The editoptions dataUrl parameter is valid only for element of edittype:select. The dataUrl parameter represent the url from where the html select element should be get.
When this option is set, the element will be filled with values from the AJAX request. The data should be a valid HTML select element with the desired options - something like:
<select>
<option value='1'>One</option>
<option value='2'>Two</option>
...
</select>
http://www.trirand.com/jqgridwiki/doku.php?id=wiki:common_rules#edittype
something like below: NOT TESTED
public JsonResult UserSelect()
{
List<User> users=db.GetUsers();
return Json(users,JsonRequestBehavior.AllowGet);
}
View: jqGrid
editoptions: { dataUrl:'<%= Url.Action("xxxx","xxxx") %>',
buildSelect: function(data) {
var response = jQuery.parseJSON(data.responseText);
var s = '<select>';
if (response && response.length) {
for (var i = 0, l=response.length; i<l ; i++) {
var ri = response[i];
s += '<option value="'+ri+'">'+ri+'</option>';
}
}
return s + "</select>";
}
}
Check this:
ASP.NET MVC $.post call returning string...need help with format for jqGrid

Related

JS grid not showing in Partial View MVC

In my project am showing js grid from partial view. so tried like this
View
<div id="searchgrid" class="col-lg-12">
#Html.Partial("ResultGrid", new List<SCM_MVC.Models.User>(), new ViewDataDictionary(this.ViewData) { { "index" , ViewData["Form"] } })
</div>
<script src="~/assets/js/jquery-1.10.2.js"></script>
<script>
var url = '#Url.Action("ResultGrid", "User", new { xEdit = ViewData["Form"]})';
$('#btnloadgrid').click(function () {
$('#searchgrid').load(url);
})
</script>
Partial View
#model IEnumerable<SCM_MVC.Models.User>
#{
/**/
/**/
#section head {
#*<link rel="stylesheet" type="text/css" href="~/SCM/jsgrid/css/demos.css" />*#
<link rel="stylesheet" type="text/css" href="~/SCM/jsgrid/css/jsgrid.css" />
<link rel="stylesheet" type="text/css" href="~/SCM/jsgrid/css/theme.css" />
<script src="~/SCM/jsgrid/js/jquery-1.8.3.js"></script>
<script src="~/SCM/jsgrid/src/jsgrid.core.js"></script>
<script src="~/SCM/jsgrid/src/jsgrid.load-indicator.js"></script>
<script src="~/SCM/jsgrid/src/jsgrid.load-strategies.js"></script>
<script src="~/SCM/jsgrid/src/jsgrid.sort-strategies.js"></script>
<script src="~/SCM/jsgrid/src/jsgrid.field.js"></script>
<script src="~/SCM/jsgrid/src/jsgrid.core.js"></script>
<script src="~/SCM/jsgrid/src/fields/jsgrid.field.text.js"></script>
<script src="~/SCM/jsgrid/src/fields/jsgrid.field.number.js"></script>
<script src="~/SCM/jsgrid/src/fields/jsgrid.field.select.js"></script>
<script src="~/SCM/jsgrid/src/fields/jsgrid.field.checkbox.js"></script>
<script src="~/SCM/jsgrid/src/fields/jsgrid.field.control.js"></script>
}
/**/
<table id="jsGrid"></table>
#section scripts {
<script src="http://js-grid.com/js/jsgrid.min.js"></script>
<script>
$(function () {
$("#jsGrid").jsGrid({
height: "70%",
width: "100%",
filtering: true,
editing: true,
inserting: true,
sorting: true,
paging: true,
autoload: true,
pageSize: 15,
pageButtonCount: 5,
deleteConfirm: "Do you really want to delete the user?",
controller: {
loadData: function (filter) {
return $.ajax({
type: "GET",
url: "/api/data",
data: filter,
dataType: "json"
});
},
insertItem: function (item) {
return $.ajax({
type: "POST",
url: "/api/data",
data: item,
dataType: "json"
});
},
updateItem: function (item) {
return $.ajax({
type: "PUT",
url: "/api/data/" + item.ID,
data: item,
dataType: "json"
});
},
deleteItem: function (item) {
return $.ajax({
type: "DELETE",
url: "/api/data/" + item.ID,
dataType: "json"
});
}
},
fields: [
{ name: "user_id", title: Resources.Resource.user_id, type: "text", width: 150 },
{ name: "username", title: Resources.Resource.user_name, type: "text", width: 50 },
{ name: "mailid", title: Resources.Resource.mailid, type: "text", width: 200 },
{ name: "role", title: Resources.Resource.role, type: "text", width: 50 },
{ name: "dept", title: Resources.Resource.dept, type: "text", width: 100 },
{ name: "designation", title: Resources.Resource.designation, type: "text", width: 100 },
{ name: "city", title: Resources.Resource.city, type: "text", width: 100 },
{ name: "country", title: Resources.Resource.country, type: "text", width: 100 },
{ type: "control" }
]
});
});
</script>
}
}
DataController
namespace SCM_MVC.Controllers
{
public class DataController : ApiController
{
// GET: Data
public IEnumerable<object> Get()
{
//ClientFilter filter = GetFilter();
//var result = DB.Client.Where(c =>
// (String.IsNullOrEmpty(filter.Name) || c.Name.Contains(filter.Name)) &&
// (String.IsNullOrEmpty(filter.Address) || c.Address.Contains(filter.Address)) &&
// (!filter.Married.HasValue || c.Married == filter.Married) &&
// (!filter.Country.HasValue || c.Country == filter.Country)
//);
Models.User xuser = new Models.User();
List<Models.User> xuserlist = new List<Models.User>();
//if (ViewData["index"] == null)
//{
// ViewData["index"] = xEdit;
//}
xuser.UserId = "US-0001";
xuser.UserName = "Robert";
xuser.Mailid = "robert#gmail.com";
xuser.Role = "Admin";
xuser.Designation = "Sales Admin";
xuser.Dept = "Sales";
xuser.State = "Tamil Nadu";
xuser.Country = "India";
xuserlist.Add(xuser);
return xuserlist;
}
}
}
UserController
public ActionResult ResultGrid(string xEdit)
{
Models.User xuser = new Models.User();
List<Models.User> xuserlist = new List<Models.User>();
xuser.UserId = "US-0001";
xuser.UserName = "Robert";
xuser.Mailid = "robert#gmail.com";
xuser.Role = "Admin";
xuser.Designation = "Sales Admin";
xuser.Dept = "Sales";
xuser.State = "Tamil Nadu";
xuser.Country = "India";
xuserlist.Add(xuser);
return PartialView(xuserlist);
}
But in Screen its not showing. What am doing wrong here?
Thanks
Am using Visual Studio 2017 ASP.Net MVC

Ext.Ajax.request not working

![
this is the project structure I am using. On adding a local URL like this below code is not working. url:'data/showStudentInfo.html']3I am using Ext Js version 4.1.1
In my application , I am having a grid, which uses a store.
On clicking "click me" button I want to redirect to the server, for test purpose I am using a basic google url,
But the class Ext.Ajax.Request is not working I think
Please help , as I am new to Ext js, I am not aware of the mistake I am making.
I am trying this in notepad++, as well as in eclipse ide (indigo version).
both with same output, Ext.Ajax.Request part not working.
It will of great help if anyone have suggestion as if I want to send
Thanking in advance
Below is my html and js file
practiseCellEditEx.js
Ext.require([
'Ext.data.*',
'Ext.Ajax.',
'Ext.grid.*'
]);
function getRandomDate() {
var from = new Date(1900, 0, 1).getTime();
var to = new Date().getTime();
var date = new Date(from + Math.random() * (to - from));
return Ext.Date.clearTime(date);
}
function createFakeData(count) {
var firstNames = ['Ed', 'Tommy', 'Aaron', 'Abe'];
var lastNames = ['Spencer', 'Maintz', 'Conran', 'Elias'];
var data = [];
for (var i = 0; i < count ; i++) {
var dob = getRandomDate();
var firstNameId = Math.floor(Math.random() * firstNames.length);
var lastNameId = Math.floor(Math.random() * lastNames.length);
var name = Ext.String.format("{0} {1}", firstNames[firstNameId], lastNames[lastNameId]);
data.push([name, dob]);
}
return data;
}
Ext.onReady(function(){
Ext.define('Person',{
extend: 'Ext.data.Model',
fields: ['Name', 'dob']
});
var store = Ext.create('Ext.data.Store', {
model: 'Person',
autoLoad: true,
proxy: {
type: 'memory',
data: createFakeData(10),
reader: {type: 'array'}
},
sorters: [{
direction:'ASC'
}]
});
Ext.create('Ext.grid.Panel', {
store: store,
plugins: [
Ext.create('Ext.grid.plugin.CellEditing', {
clicksToEdit : 1
})
],
columns: [
{
text: "Name",
width:120,
dataIndex: 'Name',
editor : {
xtype: 'textfield',
allowBlank:false
}
},
{
text: "DOB",
width: 120,
dataIndex: 'dob',
renderer: Ext.util.Format.dateRenderer('M d, Y'),
editor: {
xtype: 'datefield',
format: 'M d, Y',
minValue: '01/01/1900',
maxValue: new Date()
}
},
{
xtype: 'actioncolumn',
width: 30,
sortable: false,
menuDisabled: true,
items: [{
icon: 'http://etf-prod-projects-1415177589.us-east-1.elb.amazonaws.com/trac/docasu/export/2/trunk/client/extjs/shared/icons/fam/delete.gif',
handler: function(grid, rowIndex, colIndex) {
store.removeAt(rowIndex);
}
}]
}
],
renderTo:'example-grid',
width: 280,
height: 280
});
Ext.create('Ext.Button', {
text: 'Click me',
// renderTo: Ext.getBody(),
renderTo:'myBtn',
handler: getName
});
function getName (btn)
{
alert("hello");
var records = store.getAt(1);
alert('the name at index 1 is:'+records.get('Name'));
Ext.Ajax.request({
url : 'https://www.google.co.in/'
});
};
/*
function buttonClicked() {
Ext.MessageBox.confirm( 'Delete this part ? :' );
}*/
});
practiseCellEditEx.html
<!DOCTYPE html>
<html>
<head>
<meta charset=utf-8 />
<title>ExtJS Samples</title>
<link rel="stylesheet" type="text/css" href="../resources/css/ext-all.css" />
<script type="text/javascript" src="../adapter/ext/ext-base.js"></script>
<script type="text/javascript" src="../ext-all.js"></script>
<script type="text/javascript" src="practiseCellEditEx.js"></script>
</head>
<body>
<h2> <b>Helllo , today's Date is 02.12.2015 </b></h2>
<div id="example-grid"></div>
<!--<button id="myBtn"></button>-->
<div id="myBtn"></div>
</body>
</html>
The problems seems to be simply the request going to google.com. In my browser it is blocked because it is a cross-origin request (an ajax request to another domain), see also here for further information: https://en.wikipedia.org/wiki/Same-origin_policy.
The same code with a request to a local URL works fine.

asp.net mvc jqgrid submit grid using a button outside of the grid

I'm new to jqgrid and MVC. My Jqgrid is in multi select mode, and I want to submit all selected items on the grid to the controller by clicking on a button (tbrSave) outside of the grid.
#using (Html.BeginForm("Save", "Home"))
{
<button type="submit" id="tbrSave" class="toolbar">
<span title="Config" class="icon-32-save"></span>Save</button>
<script src="#Url.Content("~/Scripts/grid.locale-en.js")" type="text/javascript"></script>
<script src="#Url.Content("~/Scripts/jquery.jqGrid.min.js")" type="text/javascript"></script>
<script src="#Url.Content("~/Scripts/jquery-ui-1.8.11.custom.min.js")" type="text/javascript"></script>
<script type="text/javascript">
$(document).ready(function () {
var lastSelectedRow;
$('#jqGridCategoryCreate').jqGrid({
//url from wich data should be requested
url: 'CategoriesList',
//type of data
datatype: 'json',
editurl: '#Url.Action("UpdateCategory")',
//url access method type
mtype: 'POST',
//columns names
colNames: ['CategoryId', 'Category Name', 'Display Order', 'Is Featured Product'], //columns model
colModel: [
{ name: 'Id', index: 'Id', align: 'left', editable: false },
{ name: 'Name', index: 'Name', align: 'left', editable: false },
{ name: 'DisplayOrder', index: 'DisplayOrder', align: 'left', editable: true, edittype: 'text', editoptions: { maxlength: 10 }, editrules: { required: true} },
{ name: 'IsFeaturedProduct', index: 'IsFeaturedProduct', align: 'left', editable: true, edittype: 'text', edittype: 'checkbox', editoptions: { maxlength: 10, value: '1:Yes;0:No' }, formatter: 'checkbox', editrules: { required: true}}],
//pager for grid
pager: $('#jqPagerCategoryCreate'),
//number of rows per page
rowNum: 10,
//initial sorting column
sortname: 'Id',
//initial sorting direction
sortorder: 'asc',
//we want to display total records count
viewrecords: true,
multiselect: true,
//grid width
width: 'auto',
//grid height
height: 'auto',
ondblClickRow: function (id) {
if (id && id != lastSelectedRow) {
//save changes in row
jQuery('#jqGridCategoryCreate').saveRow(lastSelectedRow);
$.lastSelectedRow = id;
//trigger inline edit for row
$('#jqGridCategoryCreate').editRow(lastSelectedRow, true);
}
}
});
$('#jqGridCategoryCreate').jqGrid('navGrid', '#jqPagerCategoryCreate',
{ add: false, del: true, edit: false, search: false },
{ width: 'auto', url: '/Category/Edit' },
{ width: 'auto', url: 'SaveCustomLanguageData' },
{ width: 'auto', url: '/Category/Delete' });
function getSelectedRows() {
//make sure all items must be in view mode before submitting.
jQuery('#jqGridCategoryCreate').saveRow(lastSelectedRow);
var rows = $("#jqGridCategoryCreate").jqGrid('getGridParam', 'selarrrow');
var categories = [];
$.each(rows, function (index, rowId) {
var gridRow = $("#jqGridCategoryCreate").getRowData(rowId);
var category = { "Id": rowId,
"DisplayOrder": gridRow['DisplayOrder']
};
categories.push(category);
});
}
});
</script>
}
How can I attach getSelectedRows to the grid in order to post it to Controller ("Save").
Thanks a mil.
Nam Vo.
This would involve following steps
1) Create a anchor link on your razor view
<a id="somelink" href="">Select Multiple Accounts</a>
2) Create a click event handler for anchor link created above
$('#somelink').click(function () {
var multiplerowdata = jQuery("#grid").getGridParam('selarrrow');
$.ajax({ type: 'POST',
url: '#Url.Action("YourController", "YourActionMethod")',
data: JSON.stringify(multiplerowdata),
traditional: true,
dataType: "json",
contentType: "application/json; charset=utf-8",
success: function () { alert("row submited"); }
});})
3) At times you may get javascript error of JSON is not defined, this can be solved by inserting meta tags in shared\_layout.cshtml page as shown below
<meta http-equiv="X-UA-Compatible" content="IE=8" />
4) YourActionMethod inside YourController should like be somewhat like this
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult YourActionMethod(List<string> datarow)
{
//return "sucessfully validated";
return null;
}

How to enable excel export button for jqGrid

Hello
I want to show "export to excel" button in the pager of jqgrid. I tried many ways, read many articles/posts, but I don't see this button. Documentation does not have anything useful too. Which actions should I do to see this button
Ps. I use ASP.NET MVC
PSS. my code is
<link href="../../Scripts/jquery.UI/css/redmond/jquery-ui-1.8.1.custom.css" rel="Stylesheet"
type="text/css" />
<link href="../../Scripts/jquery.jqGrid/css/ui.jqgrid.css" rel="Stylesheet" type="text/css" />
<script type="text/javascript" src="../../Scripts/jquery.jqGrid/js/jquery-1.4.2.min.js"></script>
<script type="text/javascript" src="../../Scripts/jquery.jqGrid/js/i18n/grid.locale-ru.js"></script>
<script type="text/javascript" src="../../Scripts/jquery.jqGrid/js/jquery.jqGrid.min.js"></script>
<table id="EmployeeTable">
</table>
<div id="EmployeeTablePager">
</div>
<script type="text/javascript">
jQuery(document).ready(function () {
jQuery('#EmployeeTable').jqGrid({
url: '/Employee/EmployeeData',
datatype: "json",
mtype: 'POST',
jsonReader: {
page: "page",
total: "total",
records: "records",
root: "rows",
repeatitems: false,
id: ""
},
colNames: ['Id', 'Имя', 'Фамилия', 'Email', 'Date'],
colModel: [
{ name: 'Id', width: 20 },
{ name: 'FirstName', width: 105 },
{ name: 'LastName', width: 100 },
{ name: 'Email', width: 150 },
{ name: 'Date', width: 150, formatter: ndateFormatter }
],
pager: '#EmployeeTablePager',
excel: true,
viewrecords: true
}).jqGrid('navButtonAdd',
'#EmployeeTablePager',
{ caption: " Export to Excel ",
buttonicon: "ui-icon-bookmark",
onClickButton: genCSV, position: "last"
});
});
function genCSV() {
alert('a');
}
function ndateFormatter(cellval, opts, rwdat, _act) {
var time = cellval.replace(/\/Date\(([0-9]*)\)\//, '$1');
var date = new Date();
date.setTime(time);
return date.toDateString();
}
</script>
but I don't see the excel import button.
http://ru.magicscreenshot.com/jpg/t97BDzCIO0Q.html
why?
Assuming markup of
<table id="jqgrid"></table>
<div id="pager"></div>
Something along the lines of
$('#grid')
.jqGrid({
datatype: "clientSide",
height: 190,
colNames: headers,
colModel: model,
multiselect: true,
pager: '#pager',
pgbuttons: false,
pginput: false,
caption: "Random Data",
deselectAfterSort: false,
width: 930
})
.jqGrid('navButtonAdd',
'#pager',
{caption:" Export to Excel ",
buttonicon:"ui-icon-bookmark",
onClickButton: genCSV, position:"last"});
genCSV will be a JavaScript function that will make the call to the controller action to generate a CSV file.
Here's an example, in combination with jQuery flot. Create some data, select some grid rows and then click the generate graph button in the bottom left of the grid to plot the points. Note that this will not work in Internet Explorer less than 8 as it requires support for the HTML 5 canvas element (and I haven't bothered to include excanvas).
EDIT:
Your markup is not working because you need to initialize a navGrid before being able to set a custom button (see note on page). You can do this like so
jQuery(document).ready(function () {
jQuery('#EmployeeTable').jqGrid({
url: '/Employee/EmployeeData',
datatype: "json",
mtype: 'POST',
jsonReader: {
page: "page",
total: "total",
records: "records",
root: "rows",
repeatitems: false,
id: ""
},
colNames: ['Id', 'Имя', 'Фамилия', 'Email', 'Date'],
colModel: [
{ name: 'Id', width: 20 },
{ name: 'FirstName', width: 105 },
{ name: 'LastName', width: 100 },
{ name: 'Email', width: 150 },
{ name: 'Date', width: 150, formatter: ndateFormatter }
],
pager: '#EmployeeTablePager',
excel: true,
viewrecords: true
})
/* Need to initialize navGird before being able to set any custom buttons */
.jqGrid('navGrid', '#EmployeeTablePager', {
add: false,
edit: false,
del: false,
search: false,
refresh: false
}).jqGrid('navButtonAdd',
'#EmployeeTablePager',
{ caption: " Export to Excel ",
buttonicon: "ui-icon-bookmark",
onClickButton: genCSV, position: "last"
});
});
function genCSV() {
alert('a');
}
function ndateFormatter(cellval, opts, rwdat, _act) {
var time = cellval.replace(/\/Date\(([0-9]*)\)\//, '$1');
var date = new Date();
date.setTime(time);
return date.toDateString();
}
What I did was to create a csv file on the server and display a download link next to the grid in my view.
It's not as slick as what you have in mind but it is quick and easy to implement.
Extension method to create a csv file from a list (from another post on SO):
public static string AsCsv<T>(this IEnumerable<T> items)
where T : class
{
var csvBuilder = new StringBuilder();
var properties = typeof(T).GetProperties();
foreach (T item in items)
{
//string line = properties.Select(p => p.GetValue(item, null).ToCsvValue()).ToArray().Join(",");
string line= string.Join(", ", properties.Select(p => p.GetValue(item, null).ToCsvValue()).ToArray());
csvBuilder.AppendLine(line);
}
return csvBuilder.ToString();
}
private static string ToCsvValue<T>(this T item)
{
if (item is string)
{
return string.Format("\"{0}\"", item.ToString().Replace("\"", "\\\""));
}
double dummy;
if (double.TryParse(item.ToString(), out dummy))
{
return string.Format("{0}", item.ToString());
}
return string.Format("\"{0}\"", item.ToString());
}
Controller:
model.AListOfData.ToArray().AsCsv();
using (StreamWriter sw = System.IO.File.CreateText(errorFilePath))
{
sw.Write(values);
}
model.ErrorFullFileName = errorFilePath;
In the view:
<%=Html.ImageLink("", "AssetUpload", "DownloadErrors", "/?filename=" + Model.ErrorFullFileName, "/Content/Icons/excel.png", "Download errors and warnings", "imagelink")%>
I used this and it works pretty well
jQuery("#table_resultats").jqGrid('navGrid', "#yourpager").jqGrid( //#pager
'navButtonAdd', "#yourpager", {
caption : "Excel export",
buttonicon : "ui-icon-arrowthickstop-1-s",
onClickButton : null,
position : "first",
title : Excel export,
cursor : "pointer"
});

Asp.net MVC 2 JqueryGrid table row empty

I need some help with asp.net mvc
Controller:
<HandleError()> _
Public Class HomeController
Inherits System.Web.Mvc.Controller
Function Index() As ActionResult
ViewData("Message") = "Welcome to ASP.NET MVC!"
Return View()
End Function
Public Function GetMovieData() As ActionResult
Dim sortColumn As String = (Request.Params("sidx")).ToString()
Dim sortOrder As String = (Request.Params("sord")).ToString()
Dim pageIndex As Integer = Convert.ToInt32(Request.Params("page"))
'Remember this is NOT 0 based
Dim rowCount As Integer = Convert.ToInt32(Request.Params("rows"))
Dim movies As New Movies()
Dim movieList = movies.GetMovies()
Dim totalRecords As Integer = movieList.Count()
Dim totalPages As Integer = CInt(Math.Ceiling(CSng(totalRecords) / CSng(rowCount)))
' Dim allRecords As IQueryable(Of Movie)
' allRecords = movieList.OrderBy(Function(movie) movie.Id).Skip((pageIndex - 1) * rowCount).Take(rowCount)
'movieList = movieList.AsQueryable().OrderBy(Function(movie) movie.Id).Skip((pageIndex - 1) * rowCount).Take(rowCount)
Dim finalList = movies.Sort(movieList, sortColumn, sortOrder).Skip((pageIndex - 1) * rowCount).Take(rowCount)
Dim jsonData = New With { _
.total = totalPages, _
.page = pageIndex, _
.records = totalRecords, _
.rows = (From m In finalList _
Select New With { _
.i = m.Id, _
.cell = New String() {m.Id.Value.ToString(), m.Name, m.Director, m.ReleaseDate.ToShortDateString(), m.IMDBUserRating, m.Plot, m.ImageURL} _
} _
).ToList()
}
Return Json(jsonData)
End Function
Function About() As ActionResult
Return View()
End Function
End Class
View:
<%# Page Language="VB" MasterPageFile="~/Views/Shared/Site.Master" Inherits="System.Web.Mvc.ViewPage" %>
<asp:Content ID="indexTitle" ContentPlaceHolderID="TitleContent" runat="server">
Home Page
</asp:Content>
<asp:Content ID="PageHead" ContentPlaceHolderID="Head" runat="server" >
<link rel="stylesheet" type="text/css" media="screen" href="../../Scripts/grid/css/ui.jqgrid.css" />
<link rel="stylesheet" type="text/css" media="screen" href="../../Scripts/grid/redmond/jquery-ui-1.8.2.custom.css" />
<script src="../../Scripts/grid/js/jquery-1.4.2.min.js" type="text/javascript"></script>
<script src="../../Scripts/grid/js/i18n/grid.locale-en.js" type="text/javascript"></script>
<script src="../../Scripts/grid/js/jquery.jqGrid.min.js" type="text/javascript"></script>
</asp:Content>
<asp:Content ID="indexContent" ContentPlaceHolderID="MainContent" runat="server">
<h2><%= Html.Encode(ViewData("Message")) %></h2>
<script type="text/javascript">
$(function () {
$("#list").jqGrid({
url: '/Home/GetMovieData',
datatype: 'json',
mtype: 'GET',
colNames: ['id', 'Movie Name', 'Directed By', 'Release Date', 'IMDB Rating', 'Plot', 'ImageURL'],
colModel: [
{ name: 'id', index: 'Id', width: 55, sortable: false, hidden: true },
{ name: 'Movie Name', index: 'Name', width: 250 },
{ name: 'Directed By', index: 'Director', width: 250, align: 'right' },
{ name: 'Release Date', index: 'ReleaseDate', width: 100, align: 'right' },
{ name: 'IMDB Rating', index: 'IMDBUserRating', width: 100, align: 'right' },
{ name: 'Plot', index: 'Plot', width: 55, hidden: true },
{ name: 'ImageURL', index: 'ImageURL', width: 55, hidden: true}],
pager: '#pager',
rowNum: 10,
rowList: [10, 20, 30],
sortname: 'invid',
sortorder: 'desc',
viewrecords: true,
caption: 'My first grid'
});
});
</script>
<table id="list"></table>
<div id="pager"></div>
<p>
To learn more about ASP.NET MVC visit http://asp.net/mvc.
</p>
</asp:Content>
When I run this code the table is always empty.
Just make sure to allow GET requests when returning JSON in the GetMovieData action because by default they are disabled:
Return Json(jsonData, JsonRequestBehavior.AllowGet)
I would recommend you using FireBug which allows you to see AJAX requests and possible error messages. It's much easier to debug problems like this.

Resources