I want Telerik MVC UI AutoComplete work with my EducationEntities, but returns null. Don't know why? Here is my code:
@(Html.Kendo().AutoComplete()
.Name("students")
.DataTextField("DisplayName")
.Placeholder("Enter student name")
.DataSource(source =>
{
source.Read(read =>
{
read.Action("GetStudents", "StudentDetails").Data("onAdditionalData"); ;
}).ServerFiltering(true);
})
.HtmlAttributes(new { style = "width:240px" })
.Filter(FilterType.Contains)
.MinLength(1)
.Suggest(true)
.Height(340)
.HeaderTemplate("<div class=\"dropdown-header\">" +
"<span class=\"k-widget k-header\">Photo</span>" +
"<span class=\"k-widget k-header\">Contact info</span>" +
"</div>")
.Template("<span><img src='/Content/Images/${data}.jpg' " +
"width='20' height='20' /> ${data}</span>")
.Template("<span class=\"k-state-default\"><h3>#: data.DisplayName #</h3></span>")
.Template("<span class=\"k-state-default\"><img src=\"" + Url.Content("~/Content/Images/") + "#:data.StudentID#.jpg\" alt=\"#:data.StudentID#\" /></span>" +
"<span class=\"k-state-default\"><h3>#: data.DisplayName #</h3><p>#: data.Address #</p></span>")
)
here is my action that should return full student details.
public JsonResult GetStudents(string name)
{
var students = new EducationEntities().Student.Select(student => new Student
{
StudentID = student.StudentID,
DisplayName = student.DisplayName,
FirstName = student.FirstName,
LastName = student.LastName
});
if (!string.IsNullOrEmpty(name))
{
students = students.Where(p => p.DisplayName.Contains(name));
}
return Json(students, JsonRequestBehavior.AllowGet);
}
You should change your action to this:
Create a student model
public class StudentModel
{
public int StudentID { get; set; }
public string DisplayName { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
}
and change the action accordingly
public JsonResult GetStudents(string name)
{
//initialize the result
var students = new List<StudentModel>();
//check for filter value; if any, than filter
if (!string.IsNullOrEmpty(name))
{
students = new EducationEntities().Student
.Where(student => student.DisplayName.Contains(name))
.Select(student => new StudentModel
{
StudentID = student.StudentID,
DisplayName = student.DisplayName,
FirstName = student.FirstName,
LastName = student.LastName
}).ToList();
}
else
{
//depending on your requirements, you could return all the students when there's no filter set
students = new EducationEntities().Student.Select(student => new StudentModel
{
StudentID = student.StudentID,
DisplayName = student.DisplayName,
FirstName = student.FirstName,
LastName = student.LastName
}).ToList();
}
return Json(students, JsonRequestBehavior.AllowGet);
}
Please note that you need to explicitly call ToList()
for the query to be executed and populate your variable with the result.