始终在控制器中为mvc4中的ajax帖子获取空值 [英] Always getting null values in controller for ajax post in mvc4
本文介绍了始终在控制器中为mvc4中的ajax帖子获取空值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
嗨
i我正在尝试从我的视图到控制器的ajax帖子获取一些数据的列表。
但是当我尝试访问(在控制器中检查断点)时的属性对象(searchTerm)它总是显示空值。我试过没有字符串化和字符串化。
我的观点看起来像这样。
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"/>
}
在Controller中我有json方法。
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.
推荐答案
( function () {
( #txtSearch)。autocomplete({
来源:' @ Url.Action(GetStudents)',
minLength: 1
});
("#txtSearch").autocomplete({ source: '@Url.Action("GetStudents")', minLength: 1 });
( #btnSearch)。click( function (){
var searchTerm =
("#btnSearch").click(function () { var searchTerm =
这篇关于始终在控制器中为mvc4中的ajax帖子获取空值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文