I have a kendo grid on my razor view mvc as below:
#(Html.Kendo().Grid(Model.employeeList)
.Name("grid")
.Pageable(pager => pager
.Messages(messages => messages.Empty("No data"))
)
.Pageable(pager => pager
.PageSizes(new[] { 15, 20, 25, 50 })
)
.Filterable()
.Groupable()
.Sortable()
.Columns(columns =>
{
columns.Bound(employee => employee.employeeId);
columns.Bound(employee => employee.firstName);
columns.Bound(employee => employee.lastName);
columns.Bound(employee => employee.jobTitle);
columns.Bound(employee => employee.employeeId).ClientTemplate(
"<a href='" + Url.Action("Edit", "Employee", new { id = "#=employeeId#" }) + "'>Edit</a> | " +
"<a href='" + Url.Action("Details", "Employee", new { id = "#=employeeId#" }) + "'>Details</a> | " +
"<a href='" + Url.Action("Delete", "Employee", new { id = "#=employeeId#" }) + "'>Delete</a>"
)
.Filterable(false)
.Groupable(false)
.Sortable(false)
.Title("");
})
.DataSource(dataSource => dataSource
.Ajax()
.Read(read => read.Action("GetEmployeesList", "Employee").Data("branchData")).PageSize(15)
)
)
Along with the controller for GetEmployeesList ActionResult:
[HttpPost]
public ActionResult GetEmployeesList([DataSourceRequest]DataSourceRequest request, int branchId, bool includeNonActive)
{
IQueryable<Employee> employees;
if (includeNonActive)
{
employees = db.Employee.Where(e => e.branchId == branchId && e.isDeleted == false)
.Include(e => e.HireType).Include(e => e.HireStatus);
}
else
{
employees = db.Employee.Where(e => e.branchId == branchId && e.HireStatus.hireStatusId == 1 && e.isDeleted == false)
.Include(e => e.HireType).Include(e => e.HireStatus);
}
DataSourceResult result = employees.ToDataSourceResult(request, employee => new EmployeeViewModel
{
employeeId = employee.employeeId,
firstName = employee.firstName,
lastName = employee.lastName,
jobTitle = employee.jobTitle,
HireStatus = new HireStatus() { hireStatus = employee.HireStatus.hireStatus },
HireType = new HireType() { hireType = employee.HireType.hireType }
});
return Json(result);
}
So far, everything went well. DataSourceRequest request was passed from the grid successfully.
But then I have another post AJAX call via jQuery:
$(document).ready(function () {
$('#ddlBranchList').change(function () {
var isNonActive = $('#isNonActive')[0].checked;
var ddlValue = $('#ddlBranchList').val();
$.ajax({
type: "POST",
url: "/Employee/GetEmployeesList",
data: JSON.stringify({ branchId: ddlValue, includeNonActive: isNonActive }),
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (result) {
resultData = result;
},
error: function () {
alert("Error retrieving Employees List!");
}
}).done(function () {
var dataSource = new kendo.data.DataSource({
data: resultData.Data,
pageSize: 15
});
var grid = $('#grid').data("kendoGrid");
grid.setDataSource(dataSource);
dataSource.read();
});
});
}
A dropdown change event should trigger an ajax post to the controller, but I couldn't properly pass a proper object to DataSourceRequest request parameter. When it is posted, DataSourceRequest request is always null.
How do I pass the object correctly?
I got it working by forcing the kendo grid to re-read the data:
$('#ddlBranchList').change(function () {
var grid = $('#grid').data("kendoGrid");
grid.dataSource.read();
});
and then modify the branchData function:
function branchData() {
var isNonActive = $('#isNonActive')[0].checked;
var ddlValue = $('#ddlBranchList').val();
if (ddlValue > 0) {
branchId = ddlValue;
}
return {
branchId: branchId,
includeNonActive: isNonActive,
}
}
Related
Data Was Binding When Sortable() was clicked data was Disappearing on UI
#(Html.Kendo().Grid<Keys>(Model.baseKeysLocations).Name("SearchResultsGridLocation")
//.Sortable()
.Sortable(Sortable => Sortable.AllowUnsort(false))
.HtmlAttributes(new { style = "height: 450px" })
.Resizable(r => r.Columns(true))
.Reorderable(r => r.Columns(true))
.Scrollable(s => s.Virtual(true))
.Editable(e => e.Mode(GridEditMode.InCell))
.Pageable(p => p.Numeric(false).PreviousNext(false).Messages(m => m.Display("Total: {2}")))
.DataSource(ds => ds
.Ajax()
.AutoSync(true)
.Read(read => read.Action("Grid_KeyLocationRead", "Keys", new { #schdate = "", #drv = "" }))
.Model(m =>
{
m.Id(f => f.UniqueId);
m.Field(f => f.Schedule);
m.Field(f => f.TableId).Editable(false);
m.Field(f => f.FobId).Editable(false);
m.Field(f => f.RoomKey).Editable(false);
m.Field(f => f.Community).Editable(false);
m.Field(f => f.Lease).Editable(false);
m.Field(f => f.RoomKey).Editable(false);
m.Field(f => f.Driver).Editable(false);
m.Field(f => f.Status).Editable(false);
m.Field(f => f.FobId);
}
)
)
.Columns(columns =>
{
columns.Bound(f => f.UniqueId).Width("8rem").Hidden();
columns.Bound(f => f.TableId).Title("Id").Width("5rem").Hidden();
columns.Bound(f => f.RoomKey).Title("Key Location").Width("6rem");
columns.Bound(f => f.Community).Title("Community").Width("6rem");
columns.Bound(f => f.Lease).Title("Master").Width("6rem");
columns.Bound(f => f.Driver).Title("Driver").Width("6rem");
columns.Bound(client => client.Status).ClientTemplate("# if (Status == true) { #" + "IN" + "# } else {#" + "OUT" + "# } #").Title("Status").Width("8rem");
})
.Sortable()
)
</div>
*Data Was Binding When Sortable() was clicked data was Disappearing on UI*
*Data Was Binding *1: https://i.stack.imgur.com/qRAmu.png
When Pressing Sort Function Data Is Disappearing[2]: https://i.stack.imgur.com/LVSld.png
Trying to Sort the DataGrid ..Data Was Disappearing ..But Data Was Coming As Json Response and it was not Showing on UI with Sortable() *
function SearchLocationResults(search) {
$filter = new Array();
var leaseuid = null, complexuid = null;
if (search == true) {
if ($("#baseLocationViewModel_ComplexUId").data("kendoDropDownList").value() != '' && $("#baseLocationViewModel_ComplexUId").data("kendoDropDownList").value() != null && $("#baseLocationViewModel_ComplexUId").data("kendoDropDownList").value() != undefined) {
$filter.push({ field: "Driver", operator: "isequalto", value: $("#baseLocationViewModel_DriverUId").data("kendoDropDownList").value() });
complexuid = $("#baseLocationViewModel_ComplexUId").data("kendoDropDownList").value();
}
if ($("#baseLocationViewModel_MasterUId").data("kendoDropDownList").value() != '' && $("#baseLocationViewModel_MasterUId").data("kendoDropDownList").value() != null && $("#baseLocationViewModel_MasterUId").data("kendoDropDownList").value() != undefined) {
$filter.push({ field: "LeaseUId", operator: "isequalto", value: $("#baseLocationViewModel_MasterUId").data("kendoDropDownList").value() });
leaseuid = $("#baseLocationViewModel_MasterUId").data("kendoDropDownList").value();
}
}
$(".loadermodel").removeClass('d-none');
$.ajax({
url: '/Keys/Keys/Grid_KeyLocationRead',
type: "POST",
dataType: "json",
contentType: 'application/json; charset=utf-8',
async: false,
data: JSON.stringify({
request: $filter, schedule: $("#baseLocationViewModel_Schedule").val(), driver: $("#baseLocationViewModel_DriverUId").data("kendoDropDownList").value(), _complexUId: complexuid, _leaseUId: leaseuid
}),
cache: false,
success: function (result) {
$("#SearchResultsGridLocation").data('kendoGrid').dataSource.data([]);
$("#SearchResultsGridLocation").data('kendoGrid').dataSource.data(result);
$(".loadermodel").addClass('d-none');
},
error: function (err) {
$(".loadermodel").addClass('d-none');
}
});
}
I am not a frontend guy but I have to do something.
I have two lists:
showTeam
showMember - cascading based on showTeam.
In my HTML source code I see all the items placed as option, but when I click the DropDownList I see 0 items to pick. If I remove the selectpicker all items are visible. Any help is appreciated.
#Html.DropDownList("showTeams", null, "-Select Team-", htmlAttributes: new { id = "ddshowTeams", #class = "selectCountry selectpicker show-tick form-control" })
#Html.DropDownList("showMembers", null, "-Select Team-", htmlAttributes: new { id = "ddshowMembers", #class = " selectCountry selectpicker show-tick form-control" })
Ajax call:
debugger;
$(document).ready(function () {
//Dropdownlist Selectedchange event
$("#ddshowTeams").change(function () {
alert("pehla andar");
$("#ddshowMembers").empty();
$.ajax({
type: 'POST',
url: '#Url.Action("GetListLabels","CTComparer")',
dataType: 'json',
data: { id: $("#ddshowTeams").val() },
success: function (mems) {
console.log("which ayaeee");
// states contains the JSON formatted list
// of states passed from the controller
$.each(mems, function (i, member) {
//alert('<option value="'
// + member.Value + '">'
// + member.Text + '</option>');
$("#ddshowMembers").append('<option value="'
+ member.Value + '">'
+ member.Text + '</option>');
});
},
error: function (ex) {
alert('Failed to retrieve states.' + ex);
}
});
return false;
})
});
Json method:
[HttpPost]
public ActionResult GetListLabels(int id)
{
var list = GetLabelList(id)
.Select(p =>
new SelectListItem
{
Value = "",
Text = p.Name
});
// this.ViewBag.SourceLabels = this.GetListLabelsSelectedItems(id);
// this.ViewData["showMembers"] = this.GetListLabelsSelectedItems(0);
return Json(list, JsonRequestBehavior.AllowGet);
}
I can pass my parameters from a Kendo Grid bound columns, as shown below. But my Controller is treating it as GET. I cannot get he controller to treat it a [HTTPPOST]
#(Html.Kendo().Grid((IEnumerable<myApp.Dal.SmKpr1Value>) ViewBag.kk1)
.Name("Grid")
.Columns(columns =>
{
columns.Bound(c => c.opYear).Width(100);
columns.Bound(c => c.opPeriod).Width(100);
columns.Bound(c => c.val).Width(100)
.ClientTemplate(#Html.ActionLink("#=val#", "myAction", "myController", routeValues: null, htmlAttributes: new{ para1 = #ViewBag.para1, para2 = "#=opYear#", para3 = "#=opPeriod#",#class = "postLink k-button", onclick = "myFunction(this)" })
.ToHtmlString());
}
.
.
)
<script>
function myFunction(e) {
var _para1 = $(e).attr("para1");
var _para2 = $(e).attr("para2");
var _para3 = $(e).attr("para3");
var parameters = { param1: _para1, param2: _para2, param3: _para3 };
$.Ajax({
method: 'POST',
url: $(e).attr("href"),
data: parameters,
success: function (success)
{
alert(success);
}
});
}
</script>
I have three kendo drop downlist as below
1)
#(Html.Kendo().DropDownListFor(m => m.ProgrammeID)
.HtmlAttributes(new { data_value_primitive = "true" })
.Name("ProgrammeID")
.DataTextField("DegreeName")
.DataValueField("Id")
.OptionLabel("Select Below...")
.DataSource(source =>
{
source.Read(read =>
{
read.Action("GetProgramme", "AptitudeTset").Data("filterProgramme");
})
.ServerFiltering(true);
})
.SelectedIndex(0)
.CascadeFrom("FacultyID")
)
2)
#(Html.Kendo().DropDownListFor(m => m.SpecializationID)
.HtmlAttributes(new { data_value_primitive = "true" })
.Name("SpecializationID")
.DataTextField("SpecializationNameID")
.DataValueField("SpecializationID")
.OptionLabel("Select Below...")
.DataSource(source =>
{
source.Read(read =>
{
read.Action("GetSpecialization", "Subject").Data("filterSpecialization");
})
.ServerFiltering(true);
})
.SelectedIndex(0)
.CascadeFrom("ProgrammeID")
)
3)
#(Html.Kendo().DropDownListFor(m => m.SemesterID)
.HtmlAttributes(new { data_value_primitive = "true" })
.OptionLabel("Select Below...")
.Name("SemesterID")
.DataTextField("SemesterName")
.DataValueField("SemesterID")
.DataSource(source =>
{
source.Read(read =>
{
read.Action("GetSemester", "StudentRSRegistration").Data("loadSemester");
})
.ServerFiltering(true);
})
.SelectedIndex(0)
.CascadeFrom("SpecializationID")
.CascadeFrom("ProgrammeID"`enter code here`)
)
in here my 3rd DDL load based on 1st & 2nd DDL. But some times 2nd DDL may not has values. It can be empty..1st DDL always has values. My problem is, when 2nd DDL is null value my 3rd DDL not loading. But I want to load my 3rd DDL always. Because SemesterID is Requires. SemesterID depend on programmeID or/and SpecializationID. That's why some times 2nd DDl may have null values.
I solved this problem using Ajax call..I used 2nd DDL Cascade Event Handel like below
.Events(m=>m.Cascade("cascadesp"))
Now my 2nd DDL
#(Html.Kendo().DropDownListFor(m => m.SpecializationID)
.HtmlAttributes(new { data_value_primitive = "true" })
.Name("SpecializationID")
.DataTextField("SpecializationNameID")
.DataValueField("SpecializationID")
.OptionLabel("Select Below...")
.DataSource(source =>
{
source.Read(read =>
{
read.Action("GetSpecialization", "Subject").Data("filterSpecialization");
})
.ServerFiltering(true);
})
.Events(m=>m.Cascade("cascadesp"))
.SelectedIndex(0)
.CascadeFrom("ProgrammeID")
)
my ajax call is
function cascadesp()
{
getSemesterID($("#ProgrammeID").data("kendoDropDownList").value(),$("#SpecializationID").data("kendoDropDownList").value(),$("#SpecializationLevelID").data("kendoDropDownList").value(),$("#IntakeID").data("kendoDropDownList").value(),$("#intakeYear").val());
}
function getSemesterID(ProgrammeID, SpecializationID, SpecializationLevelID, IntakeID, intakeYear)
{
var ddl = $('#SemesterID').data("kendoDropDownList");
var URL = "/StudentRSRegistration/GetSemester/";
$.ajax({
url: URL,
data: JSON.stringify({ ProgrammeID: ProgrammeID, SpecializationID: SpecializationID, SpecializationLevelID: SpecializationLevelID, IntakeID: IntakeID, intakeYear: intakeYear }),
async: false,
cache: false,
type: "POST",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data) {
ddl.setDataSource(data);
}
});
}
now my SemeterID DDL is loding Propely
I have a problem with populating a Webgrid from an Ajax call.
I have followed the example as showed in the following thread: mvc3 populating bind webgrid from ajax however, that did not yield any results.
When I run the website, I always get the message: "Error: undefined".
when debugging the code, I am quite sure that the problem lies in the fact that the return PartialView is the problem, as my data object in the ajax success method does not get filled with data.
Here are the examples of my code:
Ajax call:
$.fn.getCardResult = function (leerling, kaart) {
$.ajax({
type: "GET",
url: '#Url.Action("GetResults","Kaarten")',
data: { leerlingID: leerling, cardID: kaart },
cache: false,
success: function (data) {
console.log(data);
if (!data.ok) {
window.alert(' error : ' + data.message);
}
else {
$('#card').html(data);
}
}
});
}
Partial View call:
<div class="card-content" id="card">
#{
if(Model.Kaart != null && Model.Kaart.Count > 0)
{
#Html.Partial("_Kaarten")
}
else
{
#: Er zijn geen kaarten beschikbaar.
}
}
</div>
Partial View:
#model List<ProjectCarrousel.Models.KaartenModel>
#{
var grid = new WebGrid(source: Model,ajaxUpdateContainerId: "card",
defaultSort: "Topicname");
grid.GetHtml(
tableStyle: "webgrid",
columns: grid.Columns(
grid.Column("Topicname", "Topic"),
grid.Column("Taskname", "Taken"),
grid.Column("Taskpoints", "Punten"),
grid.Column("Grades", "Resultaat"),
grid.Column("Date", "Datum"),
grid.Column("Teachercode", "Paraaf Docent")
)
);
}
Controller code:
public ActionResult GetResults(int leerlingID, string cardID)
{
try
{
int Ovnumber = leerlingID;
string CardId = cardID;
List<KaartenModel> kaartlijst = new List<KaartenModel>();
IEnumerable<topic> topics = _db.topic.Include("tasks.studenttotask").Where(i => i.CardID == CardId);
foreach (topic topic in topics)
{
foreach (tasks task in topic.tasks)
{
KaartenModel ka = new KaartenModel();
ka.Topicname = task.topic.Topicname;
ka.Taskname = task.Taskname;
ka.Taskpoints = task.Taskpoints;
ka.Ranks = task.Ranks;
ka.Date = task.studenttotask.Where(i => i.Ovnumber == Ovnumber).Select(d => d.Date).SingleOrDefault();
ka.Grades = task.studenttotask.Where(i => i.Ovnumber == Ovnumber).Select(d => d.Grades).SingleOrDefault();
ka.Teachercode = task.studenttotask.Where(i => i.Ovnumber == Ovnumber).Select(d => d.Teachercode).SingleOrDefault();
kaartlijst.Add(ka);
}
}
KVM.Kaart = kaartlijst;
return PartialView("_Kaarten", KVM.Kaart);
}
catch (Exception ex)
{
return Json(new { ok = false, message = ex.Message });
}
}
If anyone could help it would be greatly appreciated.
UPDATE
After fiddling about a bit I found a solution that worked for me. Below is a snippet of an updated Ajax Call:
The solution I found was too make the Success method in another way. This made sure that the Partial View rendered properly. Below is the Ajax call snippet.
$.ajax({
url: '#Url.Action("GetAjaxCall","Home")',
contentType: 'application/html; charset=utf-8',
type: 'GET',
dataType: 'html',
data: { id: id },
})
.success(function (result) {
$('#sectionContents').html(result);
})
.error(function (xhr, status) {
alert(xhr.responseText);
});
The solution I found was too make the Success method in another way. This made sure that the Partial View rendered properly. Below is the Ajax call snippet.
$.ajax({
url: '#Url.Action("GetAjaxCall","Home")',
contentType: 'application/html; charset=utf-8',
type: 'GET',
dataType: 'html',
data: { id: id },
})
.success(function (result) {
$('#sectionContents').html(result);
})
.error(function (xhr, status) {
alert(xhr.responseText);
});