Hi
i am trying an ajax post from my view to controller for getting the list of some data.
But when I tried to access (break point checked in controller) the properties of the object (searchTerm) it always showed null value. I tried without stringifying and stringifying.
My view is look like this.
@model IEnumerable<mvc41.models.student>
<link href="../../Content/jquery-ui-1.10.3.custom.min.css" rel="stylesheet" type="text/css" />
<script src="../../Scripts/jquery-1.9.1.js" type="text/javascript"></script>
<script src="../../Scripts/jquery-ui-1.10.3.custom.min.js" type="text/javascript"></script>
<script type="text/javascript">
$(function () {
$("#txtSearch").autocomplete({
source: '@Url.Action("GetStudents")',
minLength: 1
});
$("#btnSearch").click(function () {
var searchTerm = $("#txtSearch").val();
$.ajax({
url: 'Home/ListStudent',
type: 'POST',
contentType: 'application/json',
dataType: 'json',
data: JSON.stringify(searchTerm),
success: function (data) {
alert(data.success);
},
error: function () {
alert("error");
}
});
alert(searchTerm);
});
});
</script>
@if (TempData["alertMessage"]!= null) {
<script type="text/javascript">
alert("@TempData["alertMessage"]");
</script>
}
<div style="font-family:Arial">
@using (@Html.BeginForm())
{
Name:
@Html.TextBox("searchTerm", null, new { id = "txtSearch" })
<input type="submit" value="Search" id = "btnSearch"/>
}
and in Controller i have json method.
[HttpPost]
public JsonResult ListStudent(string searchTerm)
{
StudentDataContext db = new StudentDataContext();
List<student> students;
if (string.IsNullOrEmpty(searchTerm))
{
students = db.Students.ToList();
}
else
{
students = db.Students
.Where(s => s.Name.StartsWith(searchTerm)).ToList();
}
return Json(students,JsonRequestBehavior.AllowGet);
}
if anyone know where i am doing wrong please let me know.
Thanks in advance.