Binding database with kendo UI grid in ASP.NET MVC - asp.net

I am trying to implement KendoUI Grid control in my ASP.NET MVC application.
I know KendoUI guys have given numerous examples but its not working for me.
My Model code is :
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Data.SqlClient;
using System.Data.Sql;
using System.Data;
namespace KendoGrid.Models
{
public class status
{
public string SiteId { get; set; }
public string SiteName { get; set; }
public string SiteStatus { get; set; }
public static List<status> StatusInfo()
{
SqlConnection sconn = new SqlConnection(#"Data Source=DS-7071BC8FDEE6\SQLEXPRESS;Initial Catalog=AmanoTest;User ID=sa;Password=india#123");
SqlCommand cmd = new SqlCommand("select * from SiteMaster", sconn);
SqlDataAdapter sda = new SqlDataAdapter(cmd);
DataTable dt = new DataTable();
sda.Fill(dt);
status cstat;
List<status> statlist = new List<status>();
foreach (DataRow dr1 in dt.Rows)
{
cstat = new status();
cstat.SiteId = dr1[0].ToString();
cstat.SiteName = dr1[1].ToString();
cstat.SiteStatus = dr1[2].ToString();
statlist.Add(cstat);
}
return statlist;
}
}
}
My Controller Code is :
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using KendoGrid.Models;
using Kendo.Mvc.UI;
namespace KendoGrid.Controllers
{
public class statusController : Controller
{
//
// GET: /status/
public ActionResult Index()
{
return View();
}
public ActionResult Site()
{
//List<status> status = status.GetStatus();
List<status> temp = status.StatusInfo();
ViewData["table"] = temp;
return View();
}
}
}
And my view (.cshtml page) is:
#model KendoGrid.Models.status
#using Kendo.Mvc.UI
#*#{
Layout = null;
}
*#
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>Site</title>
</head>
<body>
<div>
#(Html.Kendo().Grid(Model)()
.Name("Grid")
.Columns(columns =>
{
columns.Bound(p => p.siteID);
columns.Bound(p => p.siteID);
columns.Bound(p => p.siteID);
})
.Pageable()
.Sortable()
.Scrollable()
.Filterable()
.DataSource(dataSource => dataSource
.Ajax()
.ServerOperation(false)
)
)
</div>
</body>
</html>
On executing it says :
The best overloaded method match for
'Kendo.Mvc.UI.Fluent.WidgetFactory.Grid(System.Data.DataTable)' has
some invalid arguments

Look like you are missing couple step here. Please go through this step n this might resolve your problem
http://docs.kendoui.com/getting-started/using-kendo-with/aspnet-mvc/helpers/grid/ajax-binding

You can use
var url = "/DesktopModules/MyServices/API/ATSManageClient/GetAllProjectsTechnologyBased?PortalId=210&tabid=95&Technology=" + selectedplatform;
var element = $("#grid").kendoGrid({
//debugger;
type: "odata",
dataSource: {
transport: {
read: url
},
schema: {
model: {
fields: {
RecievedDate: { type: "date" }
}
}
},
pageSize: 100
},
columnMenu: true,
scrollable: true,
filterable: true,
resizable: true,
sortable: true,
detailTemplate: kendo.template($("#template").html()),
detailInit: detailInit,
dataBound: function () {
},
columns: [
{
field: "ProjectID",
title: "Action",
template: "<a href='/Dashboard/Communication?ProjectID=#=ProjectID#'>View Communication</a>",
width: "20%"
},
//s debugger;
{
field: "ClientName",
width: "20%",
title: "Client",
template: "<a href='Accounts/UpdateClient.aspx?ClientId=#=ClientID#'> #= ClientName #</a>",
attributes: {
title: "#=ClientName#"
}
},
{
field: "ProjectTitle",
width: "20%",
title: "Project",
template: "<a href='Project/EditProject.aspx?ProjectID=#=ProjectID#'> #= ProjectTitle #</a>",
attributes: {
title: "#=ProjectTitle#"
}
},
{
field: "ColorList",
width: "20%",
template: kendo.template($("#template2").html()),
title: "Status"
},
{
field: "RecievedDate",
width: "20%",
title: "Check List Status",
template: ""
},
{
field: "RecievedDate",
width: "20%",
title: "Opened Bugs",
template: ""
}
],
pageable: {
// we don't set any DataSource here
pageSizes: [100, 150, 200]
}
});

Related

No opportunity to override name attribute for #Html.TextBoxFor in asp.net core 3.1

We are migrating our project from .net Framework 4.72 to .net core 3.1.
I have next html helper code:
#Html.TextBoxFor(Model => Model.Property, "{0:0}", htmlAttributes: new { maxlength = 8, Name = "Model2.Property" })
But when I inspect html code, name attribute is not overridden.
How can I override it?
Thank you.
You can use TextBox:
#Html.TextBox("Model2.Property",Model.Property,new { maxlength = 8})
or use asp-for and name:
<input asp-for="#Model.Property" name="Model2.Property" maxlength="8"/>
Pass data with prefix in form,and validate it in the action(ModelState.IsValid'),then return the error message to your view,but i think it's not a good idea,i think you don't need prefix in you controller action:
Here is a demo:
TestController:
public IActionResult TestPrefix([Bind(Prefix = "Model2")]DataModel model) {
if (ModelState.IsValid) {
return Ok("success");
}
string message=string.Join("; ", ModelState.Values
.SelectMany(x => x.Errors)
.Select(x => !string.IsNullOrWhiteSpace(x.ErrorMessage) ? x.ErrorMessage : x.Exception.Message.ToString()));
return Ok(message);
}
public IActionResult TestDataModel() {
return View();
}
TestDataModel.cshtml:
<form method="post">
#Html.TextBoxFor(Model => Model.Property, "{0:0}", htmlAttributes: new { maxlength = 8 })
<div style="color:red" id="errormessage">#TempData["Error"]</div>
<button onclick="postModel()">post</button>
</form>
#section scripts{
<script type="text/javascript">
function postModel() {
var formdata = new FormData();
formdata.append("Model2.Property", $("#Property").val());
$.ajax({
type: "POST",
url: '#Url.Action("TestPrefix", "Test")',
contentType: false,
processData: false,
data: formdata,
}).done(function (data) {
//$("#errormessage").append(data);
});
}
</script>
}
DataModel:
public class DataModel
{
[Required]
[Range(0,5)]
public int Property { get; set; }
}
result:

Asp.Net MVC ajax sends empty object to Controller?

I am working on a survey application with Asp.Net MVC.
I have a page named Index.cshtml which has a question table and a 'Add New' button.Once button clicked, a popup is opened with jQuery. I am calling a view from controller to fill jQuery dialog named as AddOrEdit.cshtml (child page). I am adding new question and options. Question is a textfield and its options are added in editable table. Once clicked submit button, Submit form event (save or update) is fired. Asp.Net MVC ajax sends empty object to Controller. My Question object has Option list.So one-to-many relation.
Index.cshtml and submit(ajax) function
#{
ViewBag.Title = "Soru Listesi";
}
<h2>Soru Oluşturma</h2>
<a class="btn btn-success" style="margin-bottom: 10px"
onclick="PopupForm('#Url.Action("AddOrEdit","Question")')"><i class="fa fa-plus"></i> Yeni Soru
Oluştur</a>
<table id="questionTable" class="table table-striped table-bordered accent-blue" style="width:
100%">
<thead>
<tr>
<th>Soru No</th>
<th>Soru Adı</th>
<th>Oluşturma Tarihi</th>
<th>Güncelleme Tarihi</th>
<th>Güncelle/Sil</th>
</tr>
</thead>
</table>
<link href="https://cdn.datatables.net/1.10.20/css/dataTables.bootstrap4.min.css" rel="stylesheet" />
<link href="https://stackpath.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet" />
#section Scripts{
<script src="https://cdn.datatables.net/1.10.20/js/jquery.dataTables.min.js"></script>
<script src="https://cdn.datatables.net/1.10.20/js/dataTables.bootstrap4.min.js"></script>
<script>
var Popup, dataTable;
$(document).ready(function() {
dataTable = $("#questionTable").DataTable({
"ajax": {
"url": "/Question/GetData",
"type": "GET",
"datatype": "json"
},
"columnDefs": [
{ targets: 2 }
],
"scrollX": true,
"scrollY": "auto",
"columns": [
{ "data": "QuestionId" },
{ "data": "QuestionName" },
{
"data": "CreatedDate",
"render": function(data) { return getDateString(data); }
},
{
"data": "UpdatedDate",
"render": function(data) { return getDateString(data); }
},
{
"data": "QuestionId",
"render": function(data) {
return "<a class='btn btn-primary btn-sm' onclick=PopupForm('#Url.Action("AddOrEdit", "Question")/" +
data +
"')><i class='fa fa-pencil'></i> Güncelle</a><a class='btn btn-danger btn-sm' style='margin-left:5px' onclick=Delete(" +
data +
")><i class='fa fa-trash'></i> Sil</a>";
},
"orderable": false,
"searchable": false,
"width": "150px"
}
],
"language": {
"emptyTable":
"Soru bulunamadı, lütfen <b>Yeni Soru Oluştur</b> butonuna tıklayarak yeni soru oluşturunuz. "
}
});
});
function getDateString(date) {
var dateObj = new Date(parseInt(date.substr(6)));
let year = dateObj.getFullYear();
let month = (1 + dateObj.getMonth()).toString().padStart(2, '0');
let day = dateObj.getDate().toString().padStart(2, '0');
return day + '/' + month + '/' + year;
};
function PopupForm(url) {
var formDiv = $('<div/>');
$.get(url)
.done(function(response) {
formDiv.html(response);
Popup = formDiv.dialog({
autoOpen: true,
resizable: true,
title: 'Soru Detay',
modal: true,
height: 'auto',
width: '700',
close: function() {
Popup.dialog('destroy').remove();
}
});
});
}
function SubmitForm(form) {
event.preventDefault();
if (form.checkValidity() === false) {
event.stopPropagation();
}
form.classList.add('was-validated');
if ($(form).valid()) {
var question = {};
question.questionId = 1111;
var options = new Array();
$("#questionForm TBODY TR").each(function() {
var row = $(this);
var option = {};
option.OptionId = row.find("TD").eq(0).html();
option.OptionName = row.find("TD").eq(1).html();
options.push(option);
});
question.options = options;
question.responses = new Array();
$.ajax({
type: "POST",
url: form.action,
data: JSON.stringify(question),
success: function(data) {
if (data.success) {
debugger;
Popup.dialog('close');
//dataTable.ajax.reload();
$.notify(data.message,
{
globalPosition: "top center",
className: "success",
showAnimation: "slideDown",
gap: 1000
});
}
},
error: function(req, err) {
debugger;
alert('req : ' + req + ' err : ' + err);
},
complete: function(data) {
alert('complete : ' + data.status);
}
});
}
}
function ResetForm(form) {
Popup.dialog('close');
return false;
}
function Delete(id) {
if (confirm('Bu soruyu silmek istediğinizden emin misiniz?')) {
$.ajax({
type: "POST",
url: '#Url.Action("Delete", "Question")/' + id,
success: function(data) {
if (data.success) {
dataTable.ajax.reload();
$.notify(data.message,
{
className: "success",
globalPosition: "top center",
title: "BAŞARILI"
})
}
}
});
}
}
</script>
}
QuestionController AddOrEdit action
[HttpPost]
public ActionResult AddOrEdit(Questions question)
{
using (MerinosSurveyEntities db = new MerinosSurveyEntities())
{
List<Options> options = (List<Options>) question.Options;
List<Options> existingOptions = new List<Options>(db.Options.Where(x => x.Status && x.IsActive && x.QuestionId == question.QuestionId));
foreach (Options existingOption in existingOptions)
{
Options optionUpdated = options.FirstOrDefault(x => x.OptionId == existingOption.OptionId);
if (optionUpdated != null)
{
//Update
existingOption.UpdatedDate = DateTime.Now;
existingOption.OptionName = optionUpdated.OptionName;
existingOption.IsActive = true;
existingOption.Status = true;
db.Options.Attach(existingOption);
db.Entry(existingOption).State = EntityState.Modified;
db.SaveChanges();
options.RemoveAll(x => x.OptionId == existingOption.OptionId);
}
else
{
//Delete
existingOption.Status = false;
existingOption.UpdatedDate = DateTime.Now;
db.Options.Attach(existingOption);
db.Entry(existingOption).State = EntityState.Modified;
db.SaveChanges();
}
}
foreach (Options optionNew in existingOptions)
{
optionNew.IsActive = true;
optionNew.Status = true;
optionNew.CreatedDate = DateTime.Now;
optionNew.UpdatedDate = DateTime.Now;
db.Options.Add(optionNew);
db.SaveChanges();
return Json(new { success = true, message = "Soru ve seçenekleri başarılı şekilde oluşturuldu/güncellendi." }, JsonRequestBehavior.AllowGet);
}
// db.Questions.Attach(question);
return Json(new { success = true, message = "Soru başarılı bir şekilde güncellendi." }, JsonRequestBehavior.AllowGet);
}
}
Question object
//------------------------------------------------------------------------------
// <auto-generated>
//------------------------------------------------------------------------------
namespace MerinosSurvey.Models
{
using System;
using System.Collections.Generic;
public partial class Questions
{
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2214:DoNotCallOverridableMethodsInConstructors")]
public Questions()
{
this.Responses = new HashSet<Responses>();
this.Options = new HashSet<Options>();
}
public int QuestionId { get; set; }
public string QuestionName { get; set; }
public int QuestionTypeId { get; set; }
public System.DateTime CreatedDate { get; set; }
public int CreatedUserId { get; set; }
public bool IsActive { get; set; }
public bool Status { get; set; }
public System.DateTime UpdatedDate { get; set; }
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
public virtual ICollection<Responses> Responses { get; set; }
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
public virtual ICollection<Options> Options { get; set; }
}
}
Option class
//------------------------------------------------------------------------------
// <auto-generated>
//------------------------------------------------------------------------------
namespace MerinosSurvey.Models
{
using System;
using System.Collections.Generic;
public partial class Options
{
public int OptionId { get; set; }
public string OptionName { get; set; }
public int QuestionId { get; set; }
public System.DateTime CreatedDate { get; set; }
public System.DateTime UpdatedDate { get; set; }
public bool IsActive { get; set; }
public bool Status { get; set; }
public virtual Questions Questions { get; set; }
}
}
I finally solved the problem. Because I forgot to add 'contentType' to the section where I sent an ajax request, 'ajax' was sending empty objects to the controller. But both Pascal case and camel case I tried with the result has not changed. I've seen Ajax work independently in Case.
I'm adding the section I'm editing. In this case, it works without problems.
function SubmitForm(form) {
event.preventDefault();
if (form.checkValidity() === false) {
event.stopPropagation();
}
form.classList.add('was-validated');
if ($(form).valid()) {
var question = {};
question.questionId = 1111;
question.questionName = "Name";
var options = new Array();
$("#questionForm TBODY TR").each(function() {
var row = $(this);
var option = {};
option.optionId = row.find("TD").eq(0).html();
option.optionName = row.find("TD").eq(1).html();
option.questionId = 0;
option.isActive = true;
option.status = true;
options.push(option);
});
question.options = options;
question.responses = new Array();
$.ajax({
type: "POST",
url: form.action,
data: JSON.stringify(question),
contentType: "application/json",//this is the line I forgot to add.
success: function(data) {
if (data.success) {
debugger;
Popup.dialog('close');
//dataTable.ajax.reload();
$.notify(data.message,
{
globalPosition: "top center",
className: "success",
showAnimation: "slideDown",
gap: 1000
});
}
},
error: function(req, err) {
debugger;
alert('req : ' + req + ' err : ' + err);
},
complete: function(data) {
alert('complete : ' + data.status);
}
});
}
}

Take data from different table and display as 1 joined table in asp.net mvc5

I have developed CRUD application for single table in data base, say movie database. I want display specified columns of different tables by joining them through sql query.And on inserting or editing option, all the tables must update itself automatically.
namespace AnimeshDB.Models
{
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
public partial class Animesh
{
public int ID { get; set; }
[Required(ErrorMessage = "this feild is required")]
public string Name { get; set; }
[Required(ErrorMessage = "this feild is required")]
public int Year { get; set; }
public string Plot { get; set; }
public string Poster { get; set; }
}
}
this is my view.
#model AnimeshDB.Models.Animesh
#{
Layout = null;
}
#using (Html.BeginForm("AddOrEdit", "Movie", FormMethod.Post, new { onsubmit = "return SubmitForm(this)" }))
{
#Html.HiddenFor(model => model.ID)
#*<div class="form-group">
#Html.LabelFor(model => model.ID, new { #class="control-label"})
#Html.EditorFor(model => model.ID, new {htmlAttributes= new { #class="form-control" } })
</div>*#
<div class="form-group">
#Html.LabelFor(model => model.Name, new { #class = "control-label" })
#Html.EditorFor(model => model.Name, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.Name)
</div>
<div class="form-group">
#Html.LabelFor(model => model.Year, new { #class = "control-label" })
#Html.EditorFor(model => model.Year, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.Year)
</div>
<div class="form-group">
#Html.LabelFor(model => model.Plot, new { #class = "control-label" })
#Html.EditorFor(model => model.Plot, new { htmlAttributes = new { #class = "form-control" } })
</div>
<div class="form-group">
#Html.LabelFor(model => model.Poster, new { #class = "control-label" })
#Html.EditorFor(model => model.Poster, new { htmlAttributes = new { #class = "form-control" } })
</div>
<div class="form-group">
<input type="submit" value="Submit" class="btn btn-primary" />
<input type="reset" value="Reset" class="btn" />
</div>}
this is my controller
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using AnimeshDB.Models;
using System.Data.Entity.Validation;
using System.Data.Entity;
namespace AnimeshDB.Controllers
{
public class MovieController : Controller
{
// GET: Movie
public ActionResult Index()
{
return View();
}
public ActionResult GetData()
{
using (DBModel db = new DBModel())
{
List<Animesh> movList = db.Animeshes.ToList<Animesh>();
return Json(new { data = movList }, JsonRequestBehavior.AllowGet);
}
}
[HttpGet]
public ActionResult AddOrEdit(int id = 0)
{
if (id == 0)
return View(new Animesh());
else
{
using (DBModel db = new DBModel())
{
return View(db.Animeshes.Where(x => x.ID == id).FirstOrDefault<Animesh>());
}
}
}
[HttpPost]
public ActionResult AddOrEdit(Animesh mov)
{
using (DBModel db = new DBModel())
{
try
{
if (mov.ID == 0)
{
db.Animeshes.Add(mov);
db.SaveChanges();
return Json(new { success = true, message = "Saved Successfully!!" }, JsonRequestBehavior.AllowGet);
}
else
{
db.Entry(mov).State = EntityState.Modified;
db.SaveChanges();
return Json(new { success = true, message = "Updated Successfully!!" }, JsonRequestBehavior.AllowGet);
}
}
catch (DbEntityValidationException e)
{
foreach (var eve in e.EntityValidationErrors)
{
Console.WriteLine("Entity of type \"{0}\" in state \"{1}\" has the following validation errors:",
eve.Entry.Entity.GetType().Name, eve.Entry.State);
foreach (var ve in eve.ValidationErrors)
{
Console.WriteLine("- Property: \"{0}\", Error: \"{1}\"",
ve.PropertyName, ve.ErrorMessage);
}
}
throw;
}
}
}
[HttpPost]
public ActionResult Delete(int id)
{
using (DBModel db = new DBModel())
{
Animesh mov = db.Animeshes.Where(x => x.ID == id).FirstOrDefault<Animesh>();
db.Animeshes.Remove(mov);
db.SaveChanges();
return Json(new { success = true, message = "Deleted Successfully!!" }, JsonRequestBehavior.AllowGet);
}
}
}}
And at last, this is my Index.cshtml file code
#{
ViewBag.Title = "Movie List";
}
<h2>Movie CRUD Operations</h2>
<a class="btn btn-success" style="margin-bottom:10px" onclick="PopupForm('#Url.Action("AddOrEdit","Movie")')"><i class="fa fa-plus"></i> Add New</a>
<table id="movieTable" class="table table-striped table-bordered" style="width:100%">
<thead>
<tr>
<th>Name</th>
<th>Year</th>
<th>Plot</th>
<th>Poster</th>
<th></th>
</tr>
</thead>
#section scripts
{
<script>
var Popup, dataTable;
$(document).ready(function () {
dataTable = $("#movieTable").DataTable({
"ajax": {
"url": "/Movie/GetData",
"type": "GET",
"datatype": "json"
},
"columns": [
{ "data": "Name" },
{ "data": "Year" },
{ "data": "Plot" },
{ "data": "Poster" },
{
"data": "ID", "render": function (data) {
return "<a class='btn btn-default btn-sm' onclick=PopupForm('#Url.Action("AddOrEdit","Movie")/"+ data +"')><i class='fa fa-pencil'></i> Edit</a><a class='btn btn-danger btn-sm' style='margin-left:14px' onclick=Delete("+ data +")><i class='fa fa-trash'></i> Delete</a>"
},
"orderable": false,
"width": "150px",
"searchable": false
}
],
"language": {
"emptyTable" : "No Data Found, please click on <b>Add New</b> button to Add."
}
});
});
function PopupForm(url) {
var formDiv = $('<div/>');
$.get(url)
.done(function (response) {
formDiv.html(response);
Popup = formDiv.dialog({
autoOpen: true,
resizable: false,
title: 'fill Movie details',
height: 500,
width: 700,
close: function () {
Popup.dialog('destroy').remove();
}
});
});
}
function SubmitForm(form) {
$.validator.unobtrusive.parse(form);
if ($(form).valid()) {
$.ajax({
type: "POST",
url: form.action,
data: $(form).serialize(),
success: function (data) {
if (data.success) {
Popup.dialog('close');
dataTable.ajax.reload();
$.notify(data.message, {
globalPosition: "top-center",
className: "success"
})
}
}
});
}
return false;
}
function Delete(id) {
if (confirm('Are you sure to delete this movie Record?')) {
$.ajax({
type: "POST",
url: '#Url.Action("Delete","Movie")/' + id,
success: function (data) {
if (data.success) {
dataTable.ajax.reload();
$.notify(data.message, {
globalPosition: "top-center",
className: "success"
})
}
}
});
}
}
}

How to hit JQGrid url in asp.net web form?

I am new in asp.net web form and i am unable to hit the url. Jqgrid is showing but the url to get data is not hitting. This is my aspx content named as emplosyee_list.aspx.
<%# Page Title="" Language="C#" MasterPageFile="~/main.Master" AutoEventWireup="true" CodeBehind="employee_list.aspx.cs" Inherits="CollegeManagementSystem.employee_list" %>
<asp:Content ID="Content1" ContentPlaceHolderID="head" runat="server">
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="Content" runat="server">
<div id="page-wrapper">
Back
<div class="container-fluid">
<div class="col-lg-5">
<div>
<span class="headerFont">Employee List</span>
<hr class="lining"/>
</div>
</div>
</div>
</div>
<div >
<table id="grid">
</table>
</div>
<link href="../Content/Site.css" rel="stylesheet" />
<link href="../Content/jquery.jqGrid/ui.jqgrid.css" rel="stylesheet" />
<link href="../Content/StyleSheet1.css" rel="stylesheet" />
<script src="../Scripts/jquery-1.9.1.js"></script>
<script src="../Scripts/jquery-1.9.1.min.js"></script>
<script src="../Scripts/jquery.jqGrid.js"></script>
<script src="../Scripts/jquery.jqGrid.min.js"></script>
<script src="../Scripts/employeeJquery.js"></script>
</asp:Content>
This is my employee_list.aspx.cs
{
public partial class employee_list : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
[WebMethod]
public string GetList()
{
var list = GetDataFromDB();
JavaScriptSerializer serializer = new JavaScriptSerializer();
return serializer.Serialize(list);
}
public static List<Dictionary<string, object>> GetDataFromDB()
{
DataTable dt = new DataTable();
using (SqlConnection con = new SqlConnection(#"Data Source=.;Initial Catalog='College Management System';Integrated Security=True"))
{
using (SqlCommand cmd = new SqlCommand("SELECT username, name, DOB, date, gender,address,mobile,phone,email FROM employee_details ORDER BY username", con))
{
con.Open();
SqlDataAdapter da = new SqlDataAdapter(cmd);
da.Fill(dt);
JavaScriptSerializer serializer = new JavaScriptSerializer();
List<Dictionary<string, object>> rows = new List<Dictionary<string, object>>();
Dictionary<string, object> row;
foreach (DataRow dr in dt.Rows)
{
row = new Dictionary<string, object>();
foreach (DataColumn col in dt.Columns)
{
row.Add(col.ColumnName, dr[col]);
}
rows.Add(row);
}
return rows;
}
}
}
}
}
And this is my Jqgrid code
$("#grid").jqGrid({
url: '/Admin/employee_list.aspx/GetList',
datatype: "json",
colNames: ['User', 'Name', 'DOB', 'Date',
'Gender', 'Address', "Mobile", 'Phone', 'Email', ],
colModel: [
{ name: 'User', index: 'User', width: 50, stype: 'text' },
{ name: 'Name', index: 'Name', width: 150 },
{ name: 'DOB', index: 'DOB', width: 100 },
{ name: 'Date', index: 'Date', width: 80, align: "right" },
{ name: 'Gender', index: 'Gender', width: 80, align: "right" },
{ name: 'Address', index: 'Address', width: 80, align: "right" },
{ name: 'Mobile', index: 'Mobile', width: 150, sortable: false },
{ name: 'Phone', index: 'Phone', width: 100, sortable: false },
{ name: 'Email', index: 'Email', width: 150, sortable: false }
],
pager: { enable: true, limit: 5, sizes: [2, 5, 10, 20] },
rowNum: 10,
rowList: [10, 20, 30],
sortname: 'id',
viewrecords: true,
pager :'#gridpager',
sortorder: "desc",
edit: true,
add: true,
del: true,
search: true,
searchtext: "Search",
addtext: "Add",
edittext: "Edit",
deltext: "Delete",
caption: "List Employee Details"
});
The url is not hiting and there is no error on consoleWhat is the problem
I see the following errors in your code:
you should include jQuery UI CSS on the HTML page. You can use for example <link href="https://ajax.googleapis.com/ajax/libs/jqueryui/1.11.4/themes/redmond/jquery-ui.min.css" rel="stylesheet" />
you can't include both minimized and non-minimized versions on the same page. So you should remove, for example, the references to non-minimized files jquery-1.9.1.js and jquery.jqGrid.js.
you should include the reference to i18n/grid.locale-en.js (or other locale file) before jquery.jqGrid.min.js.
You should remove from GetList() the line JavaScriptSerializer serializer = new JavaScriptSerializer(); and the call of serializer.Serialize. Instead of that the WebMethod should return object. The dot net framework will serialize the object to JSON or XML based on the contentType of HTTP request. The code of GetList method could look like
[WebMethod]
public object GetList()
{
return GetDataFromDB();
}
you should include in the option of jqGrid the following:
mtype: 'POST',
ajaxGridOptions: { contentType: "application/json" },
loadonce: true,
jsonReader: {
root: function (obj) {
// after the fix of WebMethod the next line
// can be reduced to
// return obj.d;
return typeof obj.d === "string" ? $.parseJSON(obj.d) : obj.d;
},
repeatitems: false
},
serializeGridData: function(postData) {
return JSON.stringify(postData);
},
height: "auto",
gridview: true
Moreover the value of pager parameter seems be wrong. You don't wrote which version of jqGrid you use and which fork (). I don't know specific options of Guriddo jqGrid JS, but in case of usage free jqGrid or old jqGrid in version <= 4.7, the pager parameter have wrong value.
I recommend you to remove all index properties from colModel.

JQgrid is not working in MVC4 and EntityFramework

Hi I started working on JQGrid, I followed the post which I got from an internet blog Jqgrid with MVC
My Code Looks like this:
#{
ViewBag.Title = "Home Page";
}
<h2>#ViewBag.Message</h2>
<ol class="round">
<script type="text/javascript">
jQuery(document).ready(function () {
jQuery("#list").jqGrid({
url: '/Home/DynamicGridData',
datatype: 'json',
mtype: 'POST',
colNames: ['UserId', 'FirstName', 'LastName', 'CreatedBy', 'Designation', 'City'],
colModel: [
{ name: 'UserId', index: 'UserId', width: 40, align: 'left' },
{ name: 'FirstName', index: 'FirstName', width: 40, align: 'left' },
{ name: 'LastName', index: 'LastName', width: 400, align: 'left' },
{ name: 'CreatedBy', index: 'CreatedBy', width: 400, align: 'left' },
{ name: 'Designation', index: 'Designation', width: 400, align: 'left' },
{ name: 'City', index: 'City', width: 400, aligh: 'left' }],
pager: jQuery('#pager'),
rowNum: 2,
rowList: [5, 10, 20, 50],
sortname: 'Id',
sortorder: "desc",
viewrecords: true,
imgpath: '/content/images',
caption: 'My first grid'
});
});
</script>
<%-- HTML Required--%>
<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>
</ol>
}
And my Controller looks like this:
using System;
using System.Collections.Generic;
using System.Data.Linq;
using System.Web;
using System.Web.Mvc;
using System.Linq.Expressions;
using UserInfoGrid.Models;
using System.Linq;
using System.Linq.Dynamic;
namespace UserInfoGrid.Controllers
{
public class HomeController : Controller
{
UserInfoEntities db = new UserInfoEntities();
public ActionResult Index()
{
ViewBag.Message = "Modify this template to jump-start your ASP.NET MVC application.";
return View();
}
public ActionResult About()
{
ViewBag.Message = "Your app description page.";
return View();
}
public ActionResult Contact()
{
ViewBag.Message = "Your contact page.";
return View();
}
public JsonResult DynamicGridData(string sidx, string sord, int page, int rows)
{
int pageIndex = Convert.ToInt32(page) - 1;
int pageSize = rows;
int totalRecords = db.Users.Count();
int totalPages = (int)Math.Ceiling((float)totalRecords / (float)pageSize);
// var userInfo = db.User(sidx + " " + sord).Skip(pageIndex * pageSize).Take(pageSize);
//var userInfo = db.Users.OrderBy((sidx+""+sord).Skip(pageIndex * pageSize).Take(pageSize)).ToList();
var userInfo = db.Users.OrderBy(sidx + " " + sord).Skip(pageIndex * pageSize).Take(pageSize);
var jsonData = new
{
total = totalPages,
page,
records = totalRecords,
rows = (
from u in userInfo
select new
{
i = u.UserId,
cell = new string[] { u.UserId.ToString(), u.FirstName, u.LastName, u.CreatedBy.ToString(), u.Designation, u.City.ToString() }
//cell = new string[] { "", "", "", "" }
}).ToArray()
};
return Json(jsonData);
}
}
}
}
The problem is, nothing is displaying in Index page. I am tired of trying, please help me. If you find any flaws in my code.
Thanks in advance
Please try is as below.
[HttpPost]
public JsonResult DynamicGridData(string sidx, string sord, int page, int rows)
{
//your code here
return Json(jsonData,JsonRequestBehavior.AllowGet);
}
Change this url: '/Home/DynamicGridData' to this url: '#Url.Action("DynamicGridData")'

Resources