I'm trying to connect to database from jqgrid. I have this bug in the controller, does anyone know how to fix it?
Component LINQ to Entities does not recognize the method 'System.String ToString () "and you can not translate it to express the warehouse.
When given data rigidly works.
new {id = 1, cell = new[] {"1", "zzzzzz", "xxxxxx"}}
In addition, I would like to ask how to add edit to jqgrid?
View
<asp:Content ID="indexTitle" ContentPlaceHolderID="TitleContent" runat="server">
Home Page
</asp:Content>
<asp:content contentplaceholderid="HeadContent" runat="server">
<link href="/Content/jquery-ui-1.8.7.css" rel="stylesheet" type="text/css" />
<link href="/Content/ui.jqgrid.css" rel="stylesheet" type="text/css" />
<script src="/Scripts/jquery-1.8.2.min.js" type="text/javascript"></script>
<script src="/Scripts/js/i18n/grid.locale-en.js" type="text/javascript"></script>
<script src="/Scripts/jquery.jqGrid.min.js" type="text/javascript"></script>
<script type="text/javascript">
$(function () {
$("#list").jqGrid({
url: '/Home/LinqGridData/',
datatype: 'json',
mtype: 'GET',
colNames: ['CatID', 'CatName', 'Age'],
colModel: [
{ name: 'CatID', index: 'CatID', width: 40, align: 'left' },
{ name: 'CatName', index: 'CatName', width: 40, editable: true, align: 'left' },
{ name: 'Age', index: 'Age', width: 400, align: 'left' }],
pager: jQuery('#pager'),
rowNum: 10,
rowList: [5, 10, 20, 50],
sortname: 'Id',
sortorder: "desc",
viewrecords: true,
imgpath: '/scripts/themes/coffee/images',
caption: 'My first grid'
});
jQuery("#list").jqGrid('navGrid', "#pager", { edit: true, add: true, del: true });
jQuery("#list").jqGrid('inlineNav', "#pager");
});
</script>
</asp:content>
<asp:content contentplaceholderid="MainContent" runat="server">
<h2>My Grid Data</h2>
<table id="list" class="scroll" cellpadding="0" cellspacing="0"></table>
<div id="pager" class="scroll" style="text-align:center;"></div>
</asp:content>
Model
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Web;
namespace MvcApplication2.Models
{
public class Cat
{
[Key]
public int CatID { get; set; }
public string CatName { get; set; }
public string Age { get; set; }
}
}
Controller
public ActionResult LinqGridData(string sidx, string sord, int page, int rows)
{
var context = new CatEntities();
var jsonData = new
{
total = 1, //todo: calculate
page = page,
records = context.Cats.Count(),
rows = (
from question in context.Cats
select new
{
i = question.CatID,
cell = new string[] { question.CatID.ToString(), question.CatName, question.Age }
}).ToArray()
};
return Json(jsonData, JsonRequestBehavior.AllowGet);
}
I think it's because the question for a moment it is sent to the database,
You can't send this:
question.CatID.ToString()
to SQL Server because it doesn't know what to do with the method call. If you force enumeration of the set first you can make use of .NET methods in memory:
from question in context.Cats.ToList()
The problem is going to be balancing performance. If the Cats unfiltered set is large performance will suffer as the entire table is loaded into memory. In your case you probably won't notice a difference as you're invoking ToArray() later anyway.
If possible, use Skip() and Take() to implement paging and keep your sets small.
You should also consider storing the result in a variable so that you can reference it for your rows and records properties rather than hitting the context twice.
Related
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
I would like to use JQ grid in my current MVC project but I'm running into quite a few problems trying to figure it out. I find the available documentation lacking if not missing and all the problems seem to focus on a single aspect such as getting data into the grid. Well I'm way beyond that point and I would love to see a fully functional example that does fetching data, sorting, paging, add, edit, delete and search all in one with MVC. Is there such an example anywhere on the web?
Furthermore I would like to know if I can use data annotations in conjunction with JQ grid add/edit? From what I read so far it seems that I have to define new validation rules within JQ Grid declaration and that rules that I established on the model are being ignored. Is there a way to use model rules during JQ Grid CRUD operations? I was thinking along the way of making my own jquery dialog popup with appropriate partial view loaded once a row is selected and add/edit button is clicked. however I cannot find JQ grid event which is raised when Add button is clicked. It seems to force you into using their auto generated modal popup form...
I'm not sure if all this makes any sense to any of you but any help would be appreciated. If anyone has a link to all JQ Grid events even that would be a big help... Thanks!
I just tested JQGrid and DataAnnotations on my underlying datasource and there does not appear to be any support (yet hopefully) for them.
As for the for the MVC part, are you looking to use the ASP.NET MVC Helpers provided by trirand.net? if so you can find a working example here:
http://www.trirand.net/aspnetmvc/grid/editrowinlineactionicons
-Brandon
you can try my Jq.Grid
already support for data annotation and simple searching
Razor View: Total CRUD Operation
#{
ViewBag.Title = "Home Page";
}
<table id="tbl"></table>
<div id="pager"></div>
#section scripts{
<link href="~/Content/Theme/ui.jqgrid.css" rel="stylesheet" />
<link href="~/Content/Theme/jquery-ui.min.css" rel="stylesheet" />
<script src="~/Scripts/jqGrid/jquery.jqGrid.js"></script>
<script src="~/Scripts/jqGrid/grid.inlinedit.js"></script>
<script src="~/Scripts/jqGrid/grid.locale-en.js"></script>
<script src="~/Scripts/jqGrid/jquery.sortable.js"></script>
<script>
$(function () {
var lastsel;
$("#tbl").jqGrid({
url: "/Home/GetData",
mtype: "Get",
datatype: "Json",
colNames: ["ID", "Name", "Address", "Mobile", "Salary"],
colModel: [
{ name: 'id', index: 'id', editable: false, align: 'center' },
{ name: 'name', index: 'name', editable: true },
{ name: 'address', index: 'address', editable: true },
{ name: 'mobile', index: 'mobile', editable: true },
{ name: 'salary', index: 'salary', editable: true }
],
loadonce: true,
pager: "#pager",
rowNum: 20,
height:"100%",
onSelectRow: function (id) {
if (id && id !== lastsel) {
$("#tbl").restoreRow(lastsel);
$("#tbl").editRow(id, true);
lastsel = id;
}
},
caption: "jqGrid",
editurl: "/Home/EditData",
viewrecords: true,
sortorder: "desc",
sortname: "id",
}).navGrid("#pager", { edit: false, add: false, del: true, refresh: false, search: false },
{},
{},
{
url: "/Home/DelData",
mtype: "Post",
delData: "row_id_s",
}).inlineNav("#pager", {
add: true,
addParams: {
addRowParams: {
url: "/Home/AddData",
mtype: "Post"
}
}
});
});
</script>
}
MVC Code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using jqGrid_Exam2.Models;
using System.Data.Entity;
namespace jqGrid_Exam2.Controllers
{
public class HomeController : Controller
{
public ActionResult Index()
{
return View();
}
[HttpGet]
public ActionResult GetData()
{
DBcontext db = new DBcontext();
var data = db.EmployeeTbls.ToList<EmployeeTbl>();
return Json(data,JsonRequestBehavior.AllowGet);
}
[HttpPost]
public void EditData(EmployeeTbl emp)
{
DBcontext db = new DBcontext();
db.Entry(emp).State = EntityState.Modified;
db.SaveChanges();
}
[HttpPost]
public void AddData(EmployeeTbl emp)
{
DBcontext db = new DBcontext();
db.EmployeeTbls.Add(emp);
db.SaveChanges();
}
[HttpPost]
public void DelData(string id)
{
DBcontext db = new DBcontext();
EmployeeTbl emp = db.EmployeeTbls.Find(int.Parse(id));
db.EmployeeTbls.Remove(emp);
db.SaveChanges();
}
}
}
I'm trying to implement a jqGrid with MVC.
The Model is:
public class InvoiceHeader
{
public int id { get; set; }
public DateTime invdate { get; set; }
public int clientid { get; set; }
public decimal amount { get; set; }
[Display(Name = "Invoice Number:")]
public int tax { get; set; }
public decimal total { get; set; }
[Required(ErrorMessage = "Note is a required field.")]
[Display(Name = "Note:")]
public string note { get; set; }
public int PaymentTypeId { get; set; }
public string CreatedByUsername { get; set; }
public virtual PaymentType PaymentType { get; set; }
}
My View is:
#model JQGRID.Models.InvoiceHeader
#{
ViewBag.Title = "Home Page";
}
#*<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />*# <title>My First
Grid</title>#*<link rel="stylesheet" type="text/css" media="screen" href="css/ui-lightness/jquery-ui-1.7.1.custom.css" />*#
<link rel="stylesheet" type="text/css" media="screen" href="../../Scripts/css/ui.jqgrid.css" />
<link rel="stylesheet" type="text/css" media="screen" href="../../Scripts/css/ui.multiselect.css" />
#*<link rel="stylesheet" type="text/css" media="screen" href="../../Content/themes/ui-lightness/jquery-ui-1.8.14.custom.css" />*#
<style>
html, body
{
margin: 0;
padding: 0;
font-size: 75%;
}
</style>
<script src="../../Scripts/js/jquery-1.5.2.min.js" type="text/javascript"></script>
<script src="../../Scripts/js/i18n/grid.locale-en.js" type="text/javascript"></script>
<script src="../../Scripts/js/jquery.jqGrid.min.js" type="text/javascript"></script>
#*<script src="../../Scripts/src/grid.inlinedit.js" type="text/javascript"></script>*#
<script type="text/javascript">
jQuery(document).ready(function () {
jQuery("#list").jqGrid({
url: '/Home/DynamicGridData/',
datatype: 'json',
mtype: 'POST',
colNames: ['id', 'note', 'tax', 'PaymentType', 'CreatedByUsername', 'Actions'],
colModel: [
{ name: 'id', index: 'id', hidden: true, editable: false },
{ name: 'note', index: 'note', width: 40,align:'center', editable: true, editrules: { required : true } },
{ name: 'tax', index: 'tax', width: 400, align: 'center', editable: true, editrules: { required : true } },
{ name: 'PaymentTypeId', index: 'PaymentTypeId', width: 400, align: 'center', editable: true, edittype:"select",
editoptions: { dataUrl: '/Home/PaymentTypes/' }},
{ name: 'CreatedByUsername', index: 'CreatedByUsername', hidden: true, editable: false },
{ name: 'act',index:'act',width:55,align:'center',sortable:false,formatter:'actions',
formatoptions:{
keys: true, // we want use [Enter] key to save the row and [Esc] to cancel editing.
beforeSubmit:function(postdata, formid) {
alert("Hi");
jQuery("#ValidationSummary").show('slow');
},
},}
],
pager: jQuery('#pager'),
rowNum: 10,
rowList: [5, 10, 20, 50],
sortname: 'Id',
sortorder: "desc",
viewrecords: true,
imgpath: '',
caption: 'My first grid',
editurl: '/Home/Save/'
});
jQuery("#list").navGrid('#pager', { edit: false, search: false, add: true });
});
</script>
#using (Html.BeginForm()) {
#Html.ValidationSummary()
<table id="list">
</table>
<div id="pager">
</div>}
As you can see on Save the following method in the controller is called:
public void Save(InvoiceHeader invoiceHeader)
{
if (ModelState.IsValid) {
...
try {
context.SaveChanges();
}
catch (Exception ex) {
}
}
}
What I don't understand is why when you enter this method and check invoiceHeader properties the id property is populated but the CreatedByUsername property is not populated.
I really need this property populated to save.
Could someone please explain to me why this is and how I can get CreatedByUsername populated?
Did you check the values of the Id object in your Save action? They should be the row id in the grid, not the actual Id of the object you're editing.
To prevent this, you should try adding columns for the Id and the CreatedByUserName columns and make them invisible. Also, add a key:true value to your Id column. That way, while editing, the values will get populated from those columns.
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.
In an ASP.NET MVC application using for the first time jqGrid.
I have a menu, I call "employee" from the menu in the master page like this :
<script language="javascript" type="text/javascript">
$(document).ready(function() {
$(".mnuEmployee").click(function() {
$.post("/Employee/Index", null, function(data) {
$("#text").html(data);
});
});
});
</script>
In the controller, I have this :
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Index()
{
EmployeeModel model = new EmployeeModel();
model.List = _employeeService.List();
model.Languages = _languageService.List();
return View("Index", model);
}
In the View (Index.ascx), I have this :
<script type="text/javascript">
jQuery(document).ready(function() {
jQuery("#sandgrid").jqGrid({
url: '/Employee/MyGridData/',
datatype: 'json',
mtype: 'GET',
height: 255,
width: 600,
colNames: ['Index', 'Name', 'Code'],
colModel: [
{ name: 'item_id', index: 'item_id', width: 65 },
{ name: 'item', index: 'item', width: 150 },
{ name: 'item_cd', index: 'item_cd', width: 100}],
pager: jQuery('#sandgridp'),
rowNum: 10,
rowList: [5, 10, 20, 50],
sortname: 'item_id',
sortorder: "desc",
viewrecords: true,
caption: 'Liste des employés'
});
});
</script>
<table id="sandgrid" cellpadding="0" cellspacing="0"></table>
<div id="sandgridp" style="text-align:center;"></div>
The problem is in this last part (I think), I have all datas in my model, I'd like display employee list in a jqGrid and languages (and more are coming) in classic textbox, textarea, ... How can I use the "model.List" (IList) to show in the grid ?
Thanks,
What is the reason to show languages in textbox/textarea? Did you mean select? If so then look at http://www.trirand.com/jqgridwiki/doku.php?id=wiki:common_rules, for the "select" edit type. Note that you can have multiselect list.
If you just want to display languages, then do this in your model:
model.Languages = string.Join(_languageService.List().Select(x => x.Name).ToArray(), ",");
And then jqGrid will display your languages as a string, comma-separated.
But I'd suggest you to decide (since it's not clear from the Q):
how you want to display languages/list
do you want to edit them and how
Also take a look at custom formatters http://www.trirand.com/jqgridwiki/doku.php?id=wiki:custom_formatter, you can write a function to convert your languages list into anything you want, on input you get data, on output you return string with any HTML. Don't forget "unformatter" if you need to edit the cell value. For example, I use custom formatter to display checkbox images instead of true/false text.
I'm a little confused. You have your jqGrid set up to do an AJAX query for it's data as JSON so there's no need to include in in the Index view's model.
url: '/Employee/MyGridData/',
datatype: 'json',
To use the AJAX method your controller needs a MyGridData action.
[AcceptVerbs(HttpVerbs.Get)]
public JsonResult MyGridData ()
{
var list = _employeeService.List();
return Json(list);
}
Also, the name and index properties in the colModel must match the property names in your model.