Jquery DataTable in MVC JsonResult - model-view-controller

I'm new in web and trying to draw JQuery.DataTable. This is my action:
public ActionResult Index(jQueryDataTableParamModel param)
{
var result = new List<Company>()
{
new Company(){Address = "defre", Name = "ais.com", Town = "New York"},
new Company(){Address = "defre", Name = "ais.com", Town = "New York"},
new Company(){Address = "defre", Name = "ais.com", Town = "New York"},
new Company(){Address = "defre", Name = "ais.com", Town = "New York"},
new Company(){Address = "defre", Name = "ais.com", Town = "New York"},
new Company(){Address = "defre", Name = "ais.com", Town = "New York"},
new Company(){Address = "defre", Name = "ais.com", Town = "New York"},
new Company(){Address = "defre", Name = "ais.com", Town = "New York"},
new Company(){Address = "defre", Name = "ais.com", Town = "New York"},
new Company(){Address = "defre", Name = "ais.com", Town = "New York"},
};
return Json(new{
sEcho = param.sEcho,
iTotalRecords = result.Count(),
iTotalDisplayRecords = result.Count(),
aaData = result
}, JsonRequestBehavior.AllowGet);
}
}
And this is my View:
#model IEnumerable<TestProject.Models.Company>
#{
Layout = null;
}
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<link href="~/Content/DataTables/css/jquery.dataTables.css" rel="stylesheet" />
<script src="~/Scripts/jquery-2.1.3.js"></script>
<script src="~/Scripts/DataTables/jquery.dataTables.js"></script>
<link href="~/Content/DataTables/css/jquery.dataTables.css" rel="stylesheet" />
<link href="~/Content/DataTables/css/dataTables.bootstrap.css" rel="stylesheet" />
<script src="~/Scripts/DataTables/dataTables.bootstrap.js"></script>
<script src="~/Scripts/DataTables/jquery.dataTables.min.js"></script>
<title>Index</title>
</head>
<body>
<div>
<table id="myDataTable">
<thead>
<tr>
<th>Company name</th>
<th>Address</th>
<th>Town</th>
</tr>
</thead>
<tbody>
#foreach (var item in Model)
{
<tr id="#item.ID">
<td>#item.Name</td>
<td>#item.Address</td>
<td>#item.Town</td>
</tr>
}
</tbody>
</table>
</div>
</body>
</html>
<script>
$(document).ready(function () {
$('#myDataTable').dataTable({
"bServerSide": true,
"sAjaxSource": "JQueryTableTestController/Index",
"bProcessing": true,
"aoColumns": [
{ mDataProp: "Name", sTitle: "Company Name" },
{ mDataProp: "Address", sTitle: "Address" },
{ mDataProp: "Town", sTitle: "Town" }
]
});
});
</script>
And I can't understand what am I doing wrong. I'm trying do this reading the article: http://www.codeproject.com/Articles/155422/jQuery-DataTables-and-ASP-NET-MVC-Integration-Part
Without Json result all works fine. But I wanna to do this using Json, because I want to do server side paging, filtering, sorting. Can anyone tell me: what I'm doing wrong?

Related

While implementing Data table in Spring Boot MVC Project with Thymeleaf ,no any data populate in data table

My Service,Controller and Views are :
public class LoadDataService {
public List<Employee> getEmployeeList(){
List<Employee> employeeList = new ArrayList<Employee>();
Employee employee1 = new Employee("Sridharan","Junior Blogger","5000","India");
Employee employee2 = new Employee("Arul Raj","Senior Blogger","105000","China");
Employee employee3 = new Employee("Priya","Associate","21000","Australia");
Employee employee4 = new Employee("Sam","Associate","20030","Australia");
Employee employee5 = new Employee("Ram","Associate","2020","Australia")
employeeList.add(employee5);
employeeList.add(employee4);
employeeList.add(employee3);
employeeList.add(employee2);
employeeList.add(employee1);
return employeeList;
}
#Override
public String toString() {
return "LoadDataService [getClass()=" + getClass() + ", hashCode()=" + hashCode() + ", toString()="
+ super.toString() + "]";
}
}
Controller class :
#Controller
public class JQueryDatatableController {
private static final Logger logger = LoggerFactory.getLogger(JQueryDatatableController.class);
#RequestMapping(value = "/", method = RequestMethod.GET)
public ModelAndView home(Locale locale, Model model) throws JsonGenerationException, JsonMappingException, IOException {
logger.info("Welcome home! The client locale is {}.", locale);
LoadDataService dataService = new LoadDataService();
ObjectMapper mapper = new ObjectMapper();
ModelAndView mav=new ModelAndView();
mav.addObject("employeeList", mapper.writeValueAsString(dataService.getEmployeeList()));
mav.setViewName("index");
return mav;
}
}
data table integration in HTML thymeleaf page is :
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml" xmlns:th="http://www.thymeleaf.org">
<head>
<title>Datables Demo</title>
<script type="text/javascript" th:src="#{js/jquery-1.12.1.min.js}" ></script>
<script th:src="#{js/jquery.dataTables.js}"></script>
<!--CSS StyleSheet -->
<link rel="stylesheet" type="text/css" th:href="#{/css/common.css}"/>
<link rel="stylesheet" type="text/css" th:href="#{/css/jquery.dataTables.css}">
</head>
<body>
<div>
<img class="dataTableExample" th:src="#{/images/JQueryDatatableandSpringMVC.png}">
</div>
<table id="example" class="display" cellspacing="0" width="100%" style="overflow-x:auto">
<thead>
<tr>
<th>Name</th>
<th>Designation</th>
<th>Salary</th>
<th>Country</th>
</tr>
</thead>
</table>
<script th:inline="javascript">
$(document).ready(function () {
$('#example').DataTable({
"searching": true,
"serverSide":false,
"paging":true,
"sAjaxSource":"${employeeList}",
"columns": [
{"data": "name"},
{"data": "designation"},
{"data": "salary"},
{"data": "country"}
]
})
});
</script>
</body>
</html>
Screenshot of Error
Try assigning Employee List to 'data' like below,
<script th:inline="javascript">
var empList = ${employeeList};
$(document).ready(function () {
$('#example').DataTable({
"searching": true,
"serverSide":false,
"paging":true,
"data": empList,
"columns": [
{"data": "name"},
{"data": "designation"},
{"data": "salary"},
{"data": "country"}
]
})
});
</script>
https://datatables.net/manual/data/
After multiple try and reading a lot of problem ,i find the answer
<script type="text/javascript" th:inline="javascript">
var empList = [# th:utext="${employeeList}"/];
$(document).ready(function () {
console.log(empList);
$('#example').DataTable({
"aaData":empList,
"aoColumns": [
{"mDataProp": "name"},
{"mDataProp": "designation"},
{"mDataProp": "salary"},
{"mDataProp": "country"}
]
})
});
</script>

does not contain public definition for get enumerator

my view statement shows error that " for each statement cannot operate on variables of type public definition for 'get enumerator' "
I defined all objects in model and view models. still i get this error. any solution for this?
MY VIEW:
#using Edi.ViewModel
#model viewmodel
#{
<link rel="stylesheet" type="text/css" href="~/Content/style.css" />
Layout = null;
}
<!DOCTYPE html>
<html lang="en">
<head>
<link href="~/Content/Site.css" rel="stylesheet" />
<link href="~/Content/bootstrap.min.css" rel="stylesheet" />
<link href="~/Content/bootstrap.css" rel="stylesheet" />
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
</head>
<body>
<form id="form1" name="zoo">
<div class="med">
<pre>
<fieldset id="field1">
<legend>Bill Date Range</legend>
<input type="checkbox">After <input type="date" /> <input type="checkbox">Before <input type="date" />
</fieldset>
<fieldset id="field2">
<legend>Options</legend>
<label>Facility</label> #Html.DropDownListFor(Model => Model.Facility, Model.Facility, "Select Facility", new { style = "width:200px; height :30px" })
<label>Ins Queue</label> #Html.DropDownListFor(Model => Model.InsQueue, Model.InsQueue, "Select InsQueue", new { style = "width:200px; height:30px" })
Claim type <select style="width: 100px; height:30px"><option value="ALL">All</option><option value="NEW">New</option><option value="RESUBMIT">Resubmit</option></select>
</fieldset>
<pre>
<label>No of Bills Selected </label><input type="text" size="1" /> <label> EDI send To </label> #Html.DropDownListFor(Model => Model.EdiSendTo, Model.EdiSendTo, "Select Edi", new { style = "width:200px; height :30px" }) <button type="button" onclick="">Select All</button> <button type="reset" onclick="">Refresh</button> <button type="button" onclick="">Clear All</button> <button type="button" onclick="">Edit Bill</button>
</pre>
<table id="myTable">
<tr class="hd">
<th>visit</th>
<th>billno</th>
<th>patient</th>
<th>providername</th>
<th>insname</th>
<th>payby</th>
<th>inscode</th>
<th>user</th>
<th>claimtype</th>
</tr>
-------------------#foreach (var items in Model)------------------------------
{
<tr onclick="javascript:showRow1(this);">
<td>#items.visit</td>
<td>#items.billno</td>
<td>#items.Patient</td>
<td>#items.ProviderName</td>
<td>#items.InsName</td>
<td>#items.PayBy</td>
<td>#items.InsCode</td>
<td>#items.User</td>
<td>#items.ClaimType</td>
</tr>
}
</table>
</div>
</form>
</body>
</html>
MY CONTROLLER:
namespace Edi.Controllers
{
public class HomeController :Controller
{
// GET: Home
public ActionResult Index()
{
mbill mt = new mbill();
billing db = new billing();
viewmodel vm = new viewmodel();
vm.Facility = db.Add1();
vm.EdiSendTo = db.Add2();
vm.InsQueue = db.Add3();
List<mbill> itemlist = new List<mbill>();
itemlist = db.Index();
return View("Index",vm);
}
}
}
MY MODEL:
public List<mbill> Index()
{
List<mbill> itemList = new List<mbill>();
connection();
SqlCommand cmd = new SqlCommand("procGetEDIBills", con);
cmd.CommandType = CommandType.StoredProcedure;
con.Open();
SqlDataAdapter sd = new SqlDataAdapter(cmd);
DataTable dt = new DataTable();
sd.Fill(dt);
mbill item = new mbill();
using (SqlDataReader sdr = cmd.ExecuteReader())
{
mbill io = new mbill();
while (sdr.Read())
{
io = new mbill();
io.visit = sdr["VisitDate"].ToString();
io.billno = sdr["Billno"].ToString();
io.Patient = sdr["PatientName"].ToString();
io.ProviderName = sdr["ProviderName"].ToString();
io.InsName = sdr["InsuranceName"].ToString();
io.PayBy = sdr["BillPayBy"].ToString();
io.InsCode = sdr["InsuranceId"].ToString();
io.User = sdr["QueueByUser"].ToString();
io.ClaimType = sdr["ClaimType"].ToString();
itemList.Add(io);
}
}
con.Close();
return itemList;
}
}
if i delete #using Edi.ViewModel, #model viewmodel, on view then foreach error disappears and dropdownlistfor shows does not contain definition for dropdownlistfor error.

Ajax.ActionLink does not call controller action and its view

Here, the actionlink 'Get Students' in TeacherIndex view of TeacherController must call StudentController and action method StudentList and then go to the view StudentIndex.
TeacherIndex.cshtml in TeacherController:
#model IEnumerable<StudentMVC.Models.TeacherEntity>
<script src="#Url.Content("~/Scripts/jquery-1.5.1.min.js")" type="text/javascript"></script>
<script src="#Url.Content("~/Scripts/jquery.unobtrusive-ajax.min.js")" type="text/javascript"></script>
<script src="#Url.Content("~/Scripts/jquery.validate.min.js")" type="text/javascript"></script>
<script src="#Url.Content("~/Scripts/jquery.validate.unobtrusive.min.js")" type="text/javascript"></script>
<table class="table">
<tr>
<th>
#Html.DisplayNameFor(model => model.TeacherId)
</th>
...
</tr>
#if (Model != null)
{
foreach (var item in Model)
{
<tr>
<td>
#Html.DisplayFor(modelItem => item.TeacherId)
</td>
...
<td>
#Ajax.ActionLink("Get Students", "StudentList", "Student", new { id = item.TeacherId }, new AjaxOptions { HttpMethod = "POST" })
</td>
</tr>
}
}
StudentController:
[HttpPost]
public ActionResult StudentList(int TeacherId)
{
List<StudentEntity> studentList = new List<StudentEntity>();
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["Moviedb"].ConnectionString);
SqlCommand cmd = new SqlCommand("SP_Student", con);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("#TeacherId", TeacherId);
con.Open();
SqlDataReader dr = cmd.ExecuteReader();
while (dr.Read())
{
StudentEntity student = new StudentEntity();
student.StudentId = Convert.ToInt32(dr["StudentId"]);
//...
studentList.Add(student);
}
con.Close();
return View("StudentIndex", studentList);
}
But here, instead of that, shows
Server Error in '/' Application. The resource cannot be found.
Requested URL: /Student/StudentList/1
the name of parameter should be same. use this :
#Ajax.ActionLink("Get Students", "StudentList", "Student", new { #TeacherId = item.TeacherId }, new AjaxOptions { HttpMethod = "POST" })

Kendo UI Grid sortable (and other properties) not working

I'm trying to configure a Kendo grid and I'm having issues when trying to add properties such as sorting, grouping, etc. The grid works until I add the property, then it doesn't display any of the data. I have looked at the documentation on Kendo's site and it looks as if I have everything the same as theirs but obviously I'm nissing something.
Here is the View:
#model ExampleKendoUI.Models.HeaderVm
#{
ViewBag.Title = "Index";
}
<h2>Index</h2>
<div>#Model.Name</div>
#section scripts {
<script>
// Output the data as JSON
var podata = #Html.Raw(Json.Encode(ViewBag.LineItems));
</script>
<div id="poGrid" class="k-content">
<script>
$(document).ready(function () {
$("#poGrid").kendoGrid({
dataSource: {
data: podata
},
// sortable:true, *** Uncommenting this will break the grid ***
columns: [
{
field: "Description",
title: "Desc"
},
{
field: "Quantity",
title: "Quantity"
}
]
});
});
</script>
</div>
}
Here is the controller:
namespace ExampleKendoUI.Controllers
{
public class SampleController : Controller
{
//
// GET: /Sample/
public ActionResult Index(int id)
{
var header = new HeaderVm()
{
Id = id,
Name = "Req ID"
};
var results = new List<PoLineVm>()
{
new PoLineVm()
{
Id = 1,
Description = "Some Product",
Quantity = 1.5
},
new PoLineVm()
{
Id = 2,
Description = "Another Product",
Quantity = 4.0
},
new PoLineVm()
{
Id = 3,
Description = "Last Product",
Quantity = 20
},
};
ViewBag.LineItems = results;
return View(header);
}}}
Here is the _Layout:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width" />
<title>#ViewBag.Title</title>
#Styles.Render("~/Content/css")
<link href="~/Content/kendo/2012.3.1114/kendo.default.min.css" rel="stylesheet" />
#Scripts.Render("~/bundles/modernizr")
</head>
<body>
#RenderBody()
#Scripts.Render("~/bundles/jquery")
<script src="/scripts/kendo/2012.3.1114/kendo.core.min.js"></script>
<script src="~/Scripts/kendo/2012.3.1114/kendo.data.min.js"></script>
<script src="~/Scripts/kendo/2012.3.1114/kendo.grid.min.js"></script>
#RenderSection("scripts", required: false)
</body>
</html>
You haven't included the required JavaScript files and the JavaScript error means that kendoSortable is missing. Check the documentation for the required JavaScript files: http://docs.kendoui.com/getting-started/javascript-dependencies

How to filtering gridview in MVC3?

I have gridview in Data and dropdownlist data whenever i select the Resourcename only filter that name ..........
how to write code in controller?
My contollercode
public List<BugTracker_DataHelper> GeGridView()
{
var modelList = new List<BugTracker_DataHelper>();
using (SqlConnection conn = new SqlConnection(#"Integrated Security=SSPI;Persist Security Info=False;Initial Catalog=MvcBugTracker;Data Source=SSDEV6\SQLEXPRESS"))
{
conn.Open();
SqlCommand dCmd = new SqlCommand("Select * from Resources", conn);
SqlDataAdapter da = new SqlDataAdapter(dCmd);
DataSet ds = new DataSet();
da.Fill(ds);
conn.Close();
for (int i = 0; i <= ds.Tables[0].Rows.Count - 1; i++)
{
var model = new BugTracker_DataHelper();
model.ResourceID = Convert.ToInt16(ds.Tables[0].Rows[i]["ResourceID"]);
model.ResourceName = ds.Tables[0].Rows[i]["ResourceName"].ToString();
model.EmployeEmailID = ds.Tables[0].Rows[i]["EmailID"].ToString();
//model.status = ds.Tables[0].Rows[i]["Status"].ToString();
modelList.Add(model);
}
}
return modelList;
}
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Grids(FormCollection collection,string ResourceName,int ResourceId)
{
return View();
}
My ModelCode
<%# Page Language="C#" Inherits="System.Web.Mvc.ViewPage<IEnumerable<Gridview_BugTracker.Models.BugTracker_DataHelper>>" %>
<!DOCTYPE html>
<html>
<head runat="server">
<link href="../../Content/GridStyle.css" rel="stylesheet" type="text/css" />
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<title>Grids</title>
</head>
<body>
<div>
<%: Html.DropDownList("ResourceID", (SelectList)ViewBag.ResourceID, "--Select Project--")%>
<%: Html.ValidationMessage("ResourceID")%>
<%: Html.DropDownList("ResourceName", (SelectList)ViewBag.ResourceName, "--Select Project--")%>
<%: Html.ValidationMessage("ResourceName")%>
<%
var grid = new WebGrid(source: Model, defaultSort: "ResourceName", rowsPerPage: 3);
using (Html.BeginForm())
{ %>
<div id="grid">
<%:grid.GetHtml(
tableStyle: "listing-border", headerStyle: "gridhead", footerStyle: "paging", rowStyle: "td-dark", alternatingRowStyle: "td-light",
columns:grid.Columns(
grid.Column("ResourceID"),
grid.Column("ResourceName"),
grid.Column("EmployeEmailID"),
grid.Column(
header: "",
style: "text-align-center",
format: (item) => Html.ActionLink("Edit", "Edit", new { ResourceID = item.ResourceID }))
))%>
</div>
<%} %>
</div>
</body>
</html>
how write in controller code..
please can any one help me

Resources