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>
Related
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 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,
}
}
I am using file uploader with MVC.
Following is my code :
<div class="demo-section k-content">
<input name="files" id="files" type="file" />
</div>
<script>
$(document).ready(function () {
var data = JSON.stringify({
'ReportID': '#(Model.ReportID)',
});
$("#files").kendoUpload({
async: {
saveUrl: '#Url.Action("save", "UserPage")',
//removeUrl: "remove",
autoUpload: true,
contentType: "application/json; charset=utf-8",
dataType: "json",
data: data,
}//,
});
});
on ActionResult I am using following code :
string fileName = Path.GetFileName(files.FileName);
fileName = model.ReportID + "s" + Guid.NewGuid() + extension;
Everything is working fine except the value of model.ReportID its returning NULL every time.
I am missing something here?
Try something like that:
#(Html.Kendo().Upload()
.Name("uploadFiles")
.Async(a => a
.Save("Save", "Upload")
.Remove("Remove", "Upload")
.AutoUpload(true)
.SaveField("files")
//.Batch(true)
.RemoveField("fileNames")
)
.Multiple(true)
.ShowFileList(true)
.Events(events => events
.Error("onUploadError")
.Progress("onUploadProgress")
.Complete("onUploadComplete")
.Success("onUploadSuccess")
.Select("onUploadSelect")
.Upload("onUploadAdditionalData")
.Remove("onUploadRemove"))
)
inside the onUploadAdditionalData event you can pass parameters like:
function onUploadAdditionalData(e) {
e.data = { val1: val1, val2: val2 };
}
your controller action should look like this:
public ActionResult Save(IEnumerable<HttpPostedFileBase> files, string val1, string val2)
{
//do upload handling here
}
If you check documentation http://docs.telerik.com/kendo-ui/api/javascript/ui/upload#configuration-async async.data is undocumented and i am not sure if there is such property.
You can put it directly to saveUrl:
saveUrl: '#Url.Action("save", "UserPage", new { ReportID = Model.ReportID })'
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);
});