how to Filter webgrid in mvc4 based on textbox input and dropdownList input - asp.net-mvc-4

I am still in learning curve of mvc4 . I know how to bind a webgrid in mvc4 . But my doubt is can anyone share me the idea how to bind webgrid based on filter conditions from textbox input and dropdownList input. For eg : If textbox has a date "11/15/2013" and dropdownList has the doctor name "Charles" then i need to show in gridview the list of patients who has appointment with doctor " charles " on "11/15/2013" .
code
<div id="gridContent">
#grid.GetHtml(
fillEmptyRows: true,
tableStyle: "webGrid",
alternatingRowStyle: "alternate-row",
headerStyle: "grid-header",
footerStyle: "grid-footer",
mode: WebGridPagerModes.All,
firstText: "<< First",
previousText: "< Prev",
nextText: "Next >",
lastText: "Last >>",
columns: new[] {
grid.Column("PatientID"),
grid.Column("PatientName"),
grid.Column("Age"),
grid.Column("DOB"),
grid.Column("Sex"),
grid.Column("Phone"),
grid.Column("Mobile"),
grid.Column("City"),
grid.Column("PinCode"),
// grid.Column("Dr_Remarks",header:"Remarks",style:"left"),
//grid.Column("Dr_Add1",
// header: "Bed Count",style:"right"
//),
grid.Column("",
header: "Actions",
format: #<text>
#Html.ActionLink("Edit", "EditPatient", new { id = item.PatientID }, htmlAttributes: new { #class = "link" })
|
#Html.ActionLink("Delete", "PatientList", new { id = item.PatientID },
htmlAttributes: new { #class = "link", onclick = "return confirm('Are you sure you wish to delete this record?');" })
</text>
)
})
</div>
**controller**
public ActionResult PatientList(int page = 1, string sort = "Dr_Id", string sortDir = "ASC", int id = 0)
{
if (id != 0)
{
bool isDelete = false;
isDelete = rdm_Patient.DeletePatient(id);
return View(GetPatient(page, sort, sortDir));
}
else
{
return View(GetPatient(page, sort, sortDir));
}
}
private PatientPageViewModel GetPatient(int page = 1, string sort = "Dr_Id", string sortDir = "ASC")
{
const int patientPerPage = 5;
var numPatient = rdm_Patient.CountPatient();
sortDir = sortDir.Equals("desc", StringComparison.CurrentCultureIgnoreCase) ? sortDir : "asc";
var validColumns = new[] { "PatientID", "PatientName" };
if (!validColumns.Any(c => c.Equals(sort, StringComparison.CurrentCultureIgnoreCase)))
sort = "PatientID";
var doctors = rdm_Patient.getpatientpage(page, patientPerPage, "it." + sort + " " + sortDir);
var data = new PatientPageViewModel()
{
numberOfPatient = numPatient,
patientPerPage = patientPerPage,
Patient = doctors,
};
return data;
}

As I understand of your question you need filtering in your WebGrid that doesn’t include any kind of tool to perform it. So, you have to do it manually.
You should take into account the following points:
Firstly, include a form in the View where the query criteria is collected in order to send it to the controller.
Secondly, prepare the Controller so it can receive this criteria and make it reach the Model.
Thirdly, in the Model, simply apply this criteria when counting the total amount of rows, and when obtaining the data to be displayed in the grid page.
Jose M. Aguilar in his post describes all steps which can help you to design your view and controller.

Index.cshtml:
#model MvcApplication1.Models.Employee
#{
ViewBag.Title = "Index";
}
<h2>Index</h2>
<table>
<tr>
<td>
#Html.DropDownList("lstdepartment", Model.Department_List)
</td>
</tr>
<tr>
<td>
<div id="EmployeeViewGrid">
#Html.Partial("EmployeeView",Model.Employee_Grid)
</div>
</td>
</tr>
</table>
<script type="text/javascript">
$('#lstdepartment').change(function (e) {
e.preventDefault();
var url = '#Url.Action("Filter")';
$.get(url, { department: $(this).val() }, function (result) {
debugger;
$('#EmployeeViewGrid').html(result);
});
});
</script>
Partial view:
#model List< MvcApplication1.Models.Employee>
#{
ViewBag.Title = "EmployeeView";
}
<h2>EmployeeView</h2>
<div id="gridposition" style="overflow: scroll; height: 300px; overflow-x: hidden;">
#{
var grid1 = new WebGrid(source: Model, canPage: true, rowsPerPage: 5, ajaxUpdateContainerId: "gridContent");
#grid1.GetHtml(mode: WebGridPagerModes.All, tableStyle: "webGrid",
headerStyle: "header",
alternatingRowStyle: "alt",
selectedRowStyle: "select",
rowStyle: "description",
htmlAttributes: new { id = "positionGrid" },
fillEmptyRows: false,
columns: grid1.Columns(
grid1.Column("EmployeeId", header: "EmployeeId"),
grid1.Column("EmpName", header: "EmpName"),
grid1.Column("Age", header: "Age"),
grid1.Column("Department", header: "Department"),
grid1.Column("Salary", header: "Salary")))
}
</div>
Controller:
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Entity;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using MvcApplication1.Models;
namespace MvcApplication1.Controllers
{
public class EmployeeController : Controller
{
private EmployeeDatabaseEntities1 db = new EmployeeDatabaseEntities1();
//
// GET: /Employee/
public ActionResult Index()
{
Employee _model = new Employee();
//_model.Employee_Grid = db.tbl_Employee.ToList();
var departmentlist = db.tbl_department.ToList();
_model.Department_List = (from d in departmentlist
select new SelectListItem
{
Value = d.department_id.ToString(),
Text = d.department_name
}).ToList();
var qq = (from e in db.tbl_Employee
join d in db.tbl_department on e.Department_id equals d.department_id
select new Employee
{
Department_id=e.Department_id,
EmployeeId=e.EmployeeId,
EmpName=e.EmpName,
Age=e.Age,
Department=d.department_name
}).ToList();
_model.Employee_Grid = qq;
return View("Index", _model);
}
public ActionResult Filter(string department)
{
int? department_id = Convert.ToInt32(department);
var qq = (from e in db.tbl_Employee
join d in db.tbl_department on e.Department_id equals d.department_id
where e.Department_id == department_id
select new Employee
{
Department_id = e.Department_id,
EmployeeId = e.EmployeeId,enter code here
EmpName = e.EmpName,
Age = e.Age,
Department = d.department_name
}).ToList();
return PartialView("EmployeeView",qq);
}
}
}

Related

Update Cascading Dropdown in Mvc5

Hi i want to know how to update or edit cascading dropdown like (Country,state,City)in mvc5.I have created 3 cascading dropdowns Country State city.If i select Country State will append in state dropdownn like wise city. Now i save these 3 dropdown values in table successfully. But now i stuck with edit option. I donno how to bind the saved value to these dropdowns in edit from.
My model
public class UCustomerManagementViewModel
{
public string UCountry { get; set; }
public string UState { get; set; }
public string UCity { get; set; }
}
My Controller code
public JsonResult GetCountries()
{
var Countries = db.Countries.ToList();
return Json(Countries, JsonRequestBehavior.AllowGet);
}
public JsonResult GetStatesByCountryID(string countryId)
{
int id = Convert.ToInt32(countryId);
var states = db.States.Where(d => d.CountryID == id).Select(e => new { e.UID, e.StateName }).ToList();
return Json(states, JsonRequestBehavior.AllowGet);
}
public JsonResult GetCityByStateID(string stateId)
{
int id = Convert.ToInt32(stateId);
var Cities = db.Cities.Where(d => d.StateID == id).Select(e => new { e.UID, e.CityName }).ToList();
return Json(Cities, JsonRequestBehavior.AllowGet);
}
public ActionResult Update(int id)
{
CustomerManagement cc = db.CustomerManagements.Find(id);
ViewBag.CountryID = new SelectList(db.Countries.Where(d => d.CountryID.ToString() == cc.Country.ToString()), "CountryID", "CountryName",cc.CountryID);
var ucusmanvm = new UCustomerManagementViewModel();
ucusmanvm.UCountry = cc.Country;(here i get value 1)
ucusmanvm.UState = cc.State;(here i get value 2)
ucusmanvm.UCity = cc.City;(here iget value 2)
return View(ucusmanvm);
}
here i pass all the value to view form
My View Code
$(document).ready(function () {
debugger;
$.ajax({
type: "GET",
url: '#Url.Action("GetCountries", "FrmCustomerManagement")',
datatype: "Json",
success: function (data) {
$.each(data, function (index, value) {
$('#dropdownCountry').append('<option value="' + value.CountryID + '">' + value.CountryName + '</option>');
});
}
});
$('#dropdownCountry').change(function () {
debugger;
$('#dropdownState').empty();
var cval = $('#dropdownCountry').val()
$.ajax({
type: "POST",
url: '#Url.Action("GetStatesByCountryID", "FrmCustomerManagement")',
datatype: "Json",
data: { countryId: cval },
success: function (data) {
$.each(data, function (index, value) {
$('#dropdownState').append('<option value="' + value.UID + '">' + value.StateName + '</option>');
});
}
})
});
$('#dropdownState').change(function () {
debugger;
$('#dropdownCity').empty();
var sval = $('#dropdownState').val()
$.ajax({
type: "POST",
url: '#Url.Action("GetCityByStateID", "FrmCustomerManagement")',
datatype: "Json",
data: { stateId: sval },
success: function (data) {
$.each(data, function (index, value) {
$('#dropdownCity').append('<option value="' + value.UID + '">' + value.CityName + '</option>');
});
}
})
});
#Html.DropDownList("dropdownCountry", new SelectList(string.Empty, "Value", "Text"), "Please select a country", new { #class = "form-control", #width = "80%", #value=Model.UCountry})
<div class="col-sm-8">
<label>State</label>
#Html.DropDownList("dropdownState", new SelectList(string.Empty, "Value", "Text"), "Please select a State", new { #class = "form-control", #width = "80%" , #value=Model.UState})
</div>
<div class="col-sm-8">
<label>City</label>
#Html.DropDownList("dropdownCity", new SelectList(string.Empty, "Value", "Text"), "Please select a City", new { #class = "form-control", #width = "80%" , #value=Model.Ucity})
</div>
Here in update from also i acheive Cascading dropdown using ajax. but in update form i donno how to bring the save value to drop downs(Country city, state) from controller to view (eg i saved UAE in Country Dropdown but in edit mode i donno how to bring UAE value in Country dropdown ).I passed value from controller but i donno how to bind that value in view.please any one help me to resolve this issue .

Sql, Asp.net - using left join data being multiple

My data keeps getting multiple in display even i only have one reference number in my main table which in TicketTb, can you help me how to solve this.
//TicketTb Table
//TicketNotification Table
//TicketForwardTb Table
//TicketUser Table
//TicketFwdNotification Table
This is my Controller in ASP.NET MVC, this is way of retrieving my data from my Stored Procedure.
public JsonResult GetTicket(string Username, string Usertype, string is_category)
{
Username = Session["uname"].ToString();
Usertype = Session["UserType"].ToString();
return Json(ticketDataAccessLayer.GetAllTicket(Username, Usertype, is_category), JsonRequestBehavior.AllowGet);
}
readonly string connectionString = ConnectionString.CName;
public List<Ticket> GetAllTicket(string Username, string Usertype, string is_category)
{
List<Ticket> lstTicket = new List<Ticket>();
using (SqlConnection con = new SqlConnection(connectionString))
{
SqlCommand cmd = new SqlCommand("spFetchAllTicket", con);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("Username", Username);
cmd.Parameters.AddWithValue("#Usertype", Usertype);
cmd.Parameters.AddWithValue("#is_category", is_category);
con.Open();
SqlDataReader rdr = cmd.ExecuteReader();
while (rdr.Read())
{
Ticket ticket = new Ticket();
ticket.Tid = Convert.ToInt32(rdr["Tid"]);
ticket.Details = rdr["Details"].ToString();
ticket.ErrorType = rdr["ErrorType"].ToString();
ticket.DateOccurence = rdr["DateOccurence"].ToString();
ticket.DateCreate = rdr["DateCreate"].ToString();
ticket.TicketStatus = rdr["TicketStatus"].ToString();
ticket.TicketSubject = rdr["TicketSubject"].ToString();
ticket.TicketNumber = rdr["TicketNumber"].ToString();
ticket.NotifStatus = rdr["NotifStatus"].ToString();
ticket.FStatus = rdr["FStatus"].ToString();
ticket.UserTicket = rdr["CreatedUser"].ToString();
ticket.FwdStatus = rdr["FwdStatus"].ToString();
ticket.ForwardTo = rdr["ForwardTo"].ToString();
ticket.TimeRun = rdr["TimeRun"].ToString();
ticket.TimeResponse = rdr["TimeResponse"].ToString();
ticket.RunTimeClose = rdr["RunTimeClose"].ToString();
lstTicket.Add(ticket);
}
con.Close();
This is my view .cshtml where i display my data which getting repeated even i only have one data in my main table.
<table id="ticketTable" class="display table table-hover table-striped">
<thead>
<tr>
<th>Ticket Number</th>
<th>Created By</th>
<th>Date & Time Created</th>
<th>Date & Time Occured</th>
<th>Error Type</th>
<th>Details</th>
<th>Forward To</th>
<th>Running Time</th>
<th>Response Time</th>
<th>
<select name="category" id="category" class="form-control">
<option value="">All</option>
<option value="Open">Open</option>
<option value="Closed">Closed</option>
</select>
</th>
<th>Total Run</th>
</tr>
</thead>
</table>
var dataTable = $('#ticketTable').DataTable({
"language": {
"emptyTable": "No Transaction"
},
ajax: {
url: "/Ticket/GetTicket/" + is_category,
dataType: "json",
retrieve: "true",
processing: "true",
serverSide: "true",
type: "POST",
dataSrc: "",
data: { is_category: is_category },
},
columnDefs: [
{
targets: [9],
orderable: false,
},
],
columns: [
{
data: "TicketNumber",
render: function (data, type, row, meta) {
var ticketNumber = row.TicketNumber
var NotifStatus = row.NotifStatus
var Fwd = '<span class="badge badge-danger">' + row.FStatus + '</span>'
if ("#ViewBag.Usertype" === 'Admin') {
if (NotifStatus == 0) {
return '<span class="badge badge-danger">New</span> ' + ticketNumber + ' ';
}
else
{
return ticketNumber;
}
}
else if ("#ViewBag.Usertype" === 'User')
{
return Fwd + " " + ticketNumber;
}
},
},
{
data: "UserTicket"
},
{
data: "DateCreated",
render: function (data, type, row) {
var DateTime = row.DateCreate;
return DateTime;
},
},
{
data: "DateOccurence",
render: function (data, type, row) {
var DateTime = row.DateOccurence;
return DateTime;
},
},
{
data: "ErrorType"
},
{
data: "TicketNumber",
render: function (data, type, row, meta) {
return '<button type="button" class="btn btn-info viewdetails" id="' + data + '">View</button>';
},
},
{
data: "ForwardTo"
},
{
data: "TimeRun"
},
{
data: "TimeResponse"
},
{
data: "TicketStatus"
},
{
data: "RunTimeClose"
},
]
});
//SQL CODE
ALTER procedure [dbo].[spFetchAllTicket]
(
#Usertype nvarchar(50)
)
as
Begin
IF #Usertype='Admin'
begin
select TicketTb.* , TicketNotification.* , TicketForwardTb.* , TicketUser.* , TicketFwdNotification.*
from TicketTb
LEFT JOIN TicketNotification on TicketTb.TicketNumber = TicketNotification.NotifTicketID
LEFT JOIN TicketForwardTb on TicketTb.TicketNumber = TicketForwardTb.FTicketNumber
LEFT JOIN TicketUser on TicketTb.UserTicket = TicketUser.UserName
LEFT JOIN TicketFwdNotification on TicketTb.TicketNumber = TicketFwdNotification.FwdTicketNumber
order by TicketTb.Tid
end

Records Not Displaying in jquery.datatables using server side pagination processing

i am trying to get jquery.datatables working using server side processing and pagination. I used the following example article as a guide because its close to the version VS2017 that i am using-
https://www.c-sharpcorner.com/article/filtering-jquery-data-table-server-side-using-mvc-and-entity-framework/
When I run the application i get the following error:
DataTables warning: table id=tblrtr - Requested unknown parameter 'Id' for row 0, column 0. For more information about this error, please see http://datatables.net/tn/4
and an empty grid that shows 10 blank lines and the right page count.
I have debugged the code and it finds all the records and values, and indeed the finalresult variable does return the contents of the 10 rows- but they dont seem to make it to the datatable grid.
Here is the controller code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Rendering;
using Microsoft.EntityFrameworkCore;
using RTMGMTTest.Models;
namespace RTMGMTTest.Controllers
{
public class ReportsToRecordsController : Controller
{
private readonly RTMGMTContext _context;
public ReportsToRecordsController(RTMGMTContext context)
{
_context = context;
}
// GET: ReportsToRecords
public async Task<IActionResult> Index()
{
//return View(await _context.ReportsToRecords.ToListAsync());
return View();
}
[HttpPost]
public JsonResult RTRList(DTParameters param)
{
int TotalCount = 0;
var filtered = this.GetRTRFiltered(param.Search.Value, param.SortOrder, param.Start, param.Length, out TotalCount);
var RTRList = filtered.Select(o => new ReportsToRecords()
{
Id = o.Id,
ReportingId = o.ReportingId,
Title = o.Title,
Name = o.Name,
ReportsToId = o.ReportsToId,
EmployeeId = o.EmployeeId
});
DTResult<ReportsToRecords> finalresult = new DTResult<ReportsToRecords>
{
draw = param.Draw,
data = RTRList.ToList(),
recordsFiltered = TotalCount,
recordsTotal = filtered.Count
};
return Json(finalresult);
}
and
//for server side processing
public List<ReportsToRecords> GetRTRFiltered(string search, string sortOrder, int start, int length, out int TotalCount)
{
var result = _context.ReportsToRecords.Where(p => (search == null
|| (p.ReportingId != null && p.ReportingId.ToLower().Contains(search.ToLower())
|| p.Title != null && p.Title.ToLower().Contains(search.ToLower())
|| p.Name != null && p.Name.ToLower().Contains(search.ToLower())
|| p.ReportsToId != null && p.ReportsToId.ToLower().Contains(search.ToLower())
|| p.EmployeeId!= null && p.EmployeeId.ToLower().Contains(search.ToLower())
))).ToList();
TotalCount = result.Count;
result = result.Skip(start).Take(length).ToList();
switch (sortOrder)
{
case "ReportingId":
result = result.OrderBy(a => a.ReportingId).ToList();
break;
case "Title":
result = result.OrderBy(a => a.Title).ToList();
break;
case "Name":
result = result.OrderBy(a => a.Name).ToList();
break;
case "ReportsToId":
result = result.OrderBy(a => a.ReportsToId).ToList();
break;
case "EmployeeId":
result = result.OrderBy(a => a.EmployeeId).ToList();
break;
default:
result = result.AsQueryable().ToList();
break;
}
return result.ToList();
}
The view page looks as follows:
#model IEnumerable<RTMGMTTest.Models.ReportsToRecords>
#{
ViewData["Title"] = "Index";
Layout = "~/Views/Shared/_Layout.cshtml";
}
<h2>Index</h2>
<p>
<a asp-action="Create">Create New</a>
</p>
<script src="https://ajax.aspnetcdn.com/ajax/jquery/jquery-3.3.1.min.js"></script>
<link rel="stylesheet" href="https://cdn.datatables.net/1.10.16/css/jquery.dataTables.min.css" />
<script src="https://cdn.datatables.net/1.10.16/js/jquery.dataTables.min.js"></script>
<script>
$(document).ready(function () {
if ($.fn.DataTable.isDataTable('#tblrtr')) {
$('#tblrtr').dataTable().fnDestroy();
$('#tblrtr').dataTable().empty();
}
var complete = $('#tblrtr').DataTable(
{
"serverSide": true,
"destroy": true,
"processing": true,
"ajax":
{
url: "/ReportsToRecords/RTRList",
method: "POST"
},
"columns": [
{ "data": "Id"},
{ "data": "ReportingId" },
{ "data": "Title" },
{ "data": "Name" },
{ "data": "ReportsToId" },
{ "data": "EmployeeId" }
]
}
);
/// Following code is for filter input to apply filter only on Enter
var itm = $("#tblrtr_filter input")
itm.unbind();
itm.keyup(function (e) {
//enter or tab
if (e.keyCode == 13) {
complete.search(this.value).draw();
}
});
});
</script>
<table class="table" id="tblrtr">
<thead>
<tr>
<th>
Id
</th>
<th>
ReportingId
</th>
<th>
Title
</th>
<th>
Name
</th>
<th>
ReportsToId
</th>
<th>
EmployeeId
</th>
<th></th>
</tr>
</thead>
<tbody></tbody>
</table>
Does anyone know what would cause the data returned from the controller to not display and cause the resulting message? Thanks.

Remember selected checkboxes across paginated pages

I am displaying data in a table and doing some paging and sorting. I have a checkbox for everyrow.
When I move from one page to another, I will like to keep the checkboxes checked if they were checked.
I dont want the checked boxes to uncheck as I navigate from page to page. How do i achieve that?
Here is my jquery.
<script type="text/javascript">
$(document).ready(function () {
$(".header").click(function (evt) {
var sortfield = $(evt.target).data("sortfield");
if ($("#SortField").val() == sortfield)
{
if($("#SortDirection").val()=="ascending")
{
$("#SortDirection").val("descending");
}
else
{
$("#SortDirection").val("ascending");
}
}
else
{
$("#SortField").val(sortfield);
$("#SortDirection").val("ascending");
}
evt.preventDefault();
$("form").submit();
});
$(".pager").click(function (evt) {
var pageindex = $(evt.target).data("pageindex");
$("#CurrentPageIndex").val(pageindex);
evt.preventDefault();
$("form").submit();
});
});
</script>
Here is my html page
<body>
<h1>List of Customers</h1>
#{
PageSortOnlineEx.Models.SortingPagingInfo info = ViewBag.SortingPagingInfo;
}
#using (Html.BeginForm("Index", "Home", FormMethod.Post))
{
#Html.Hidden("SortField", info.SortField)
#Html.Hidden("SortDirection", info.SortDirection)
#Html.Hidden("PageCount", info.PageCount)
#Html.Hidden("PageSize", info.PageSize)
#Html.Hidden("CurrentPageIndex", info.CurrentPageIndex)
<table border="1" cellpadding="10">
<tr>
<th>Select</th>
<th>CustomerID</th>
<th>CompanyName</th>
<th>ContactName</th>
<th>Country</th>
</tr>
#foreach (var item in Model)
{
<tr>
<td>#Html.CheckBox("select", false)</td>
<td>#item.CustomerID</td>
<td>#item.CompanyName</td>
<td>#item.ContactName</td>
<td>#item.Country</td>
</tr>
}
<tr>
<td colspan="4">
#for (var i = 0; i < info.PageCount; i++)
{
if (i == info.CurrentPageIndex)
{
<span>#(i + 1)</span>
}
else
{
#(i + 1)
}
}
</td>
</tr>
</table>
}
</body>
Here is my controller code
public ActionResult Index()
{
using (NorthwindEntities db = new NorthwindEntities())
{
SortingPagingInfo info = new SortingPagingInfo();
info.SortField = "CustomerID";
info.SortDirection = "ascending";
info.PageSize = 10;
info.PageCount = Convert.ToInt32(Math.Ceiling((double)(db.Customers.Count() / info.PageSize)));
info.CurrentPageIndex = 0;
var query = db.Customers.OrderBy(c => c.CustomerID).Take(info.PageSize);
ViewBag.SortingPagingInfo = info;
List<Customer> model = query.ToList();
return View(model);
}
}
[HttpPost]
public ActionResult Index(SortingPagingInfo info)
{
using (NorthwindEntities db = new NorthwindEntities())
{
IQueryable<Customer> query = null;
switch (info.SortField)
{
case "CustomerID":
query = (info.SortDirection == "ascending" ? db.Customers.OrderBy(c => c.CustomerID) : db.Customers.OrderByDescending(c => c.CustomerID));
break;
case "CompanyName":
query = (info.SortDirection == "ascending" ? db.Customers.OrderBy(c => c.CompanyName) : db.Customers.OrderByDescending(c => c.CompanyName));
break;
case "ContactName":
query = (info.SortDirection == "ascending" ? db.Customers.OrderBy(c => c.ContactName) : db.Customers.OrderByDescending(c => c.ContactName));
break;
case "Country":
query = (info.SortDirection == "ascending" ? db.Customers.OrderBy(c => c.Country) : db.Customers.OrderByDescending(c => c.Country));
break;
}
query = query.Skip(info.CurrentPageIndex * info.PageSize).Take(info.PageSize);
ViewBag.SortingPagingInfo = info;
List<Customer> model = query.ToList();
return View(model);
}
}

sample of kendo combo for relation table with id and value

i'm using kendo ui in my asp.net mvc 4 with razor views and encounter problem with kendo combo when the list load from an action via ajax with sending parameters to the server like the sample here:HERE
becuase the table has more then 2,000 rows.
when i load the edit page, the combo load and filter the data as expected, but the value of this field is - [object object].
i did declare the .DataTextField("ProffName") + .DataValueField("ID")
My ClientsController:
public ActionResult Edit(int id = 0)
{
Clients clients = db.Clients.Find(id);
if (clients == null)
{
return HttpNotFound();
}
ViewData["MyAgency"] = new SelectList(db.Agency, "ID", "AgentName", clients.AgencyId);
ViewData["MyCategory1"] = new SelectList(db.CategoryTbl, "ID", "category", clients.CategoryId);
List<SelectListItem> obj = new List<SelectListItem>();
obj.Add(new SelectListItem { Text = "male", Value = "1" });
obj.Add(new SelectListItem { Text = "female", Value = "2" });
obj.Add(new SelectListItem { Text = "choose", Value = "0" });
ViewData["MyMin"] = obj;
ViewBag.ProffID = new SelectList(db.ProfTBL, "ID", "ProffName", clients.ProffID);
ViewBag.Metapel = new SelectList(db.Workers, "ID", "WorkerName", clients.Metapel);
return View(clients);
}
My ProffController:
public ActionResult ProffVM_Read(string text)
{
var Proff_Tbl = db.ProfTBL.Select(proff => new ProffVm { ID = proff.ID, ProffName = proff.ProffName });
if (!string.IsNullOrEmpty(text))
{
Proff_Tbl = Proff_Tbl.Where(p => p.ProffName.Contains(text));
}
return Json(Proff_Tbl, JsonRequestBehavior.AllowGet);
}
and the Kendo combo:
#Html.Label("Proff")
#(Html.Kendo().ComboBoxFor(model => model.ProffID)
.Name("proffCbo")
.DataTextField("ProffName")
.DataValueField("ID")
.Events(e => e
.Select("proffCbo_select")
.Change("proffCbo_change")
)
.DataSource(source =>
{
source.Read(read =>
{
read.Action("ProffVM_Read", "Proff")
.Data("onAdditionalData");
});
})
)
where am i wrong ???
i can change this combo to textbox but... i have to realize the magic.
Thanks
Change these two lines
var Proff_Tbl = db.ProfTBL.Select(proff => new ProffVm { ID = proff.ID, ProffName = proff.ProffName });
Proff_Tbl = Proff_Tbl.Where(p => p.ProffName.Contains(text));
to
var Proff_Tbl = db.ProfTBL.Select(proff => new ProffVm { ID = proff.ID, ProffName = proff.ProffName }).ToList();
Proff_Tbl = Proff_Tbl.Where(p => p.ProffName.Contains(text)).ToList();