我正在尝试从控制器获取数据,使用ajax但不成功。以下是我的代码,这工作正常,但没有获取数据。如果我在代码中遗漏了某些内容,请帮助并纠正我。
以下是我的代码。
@model MvcAppLearn.Models.Student
<!DOCTYPE html>
<html lang="en">
<head>
<title>This is tile</title>
</head>
<body>
@using (Html.BeginForm("Index", "popup", FormMethod.Get, new { id = "myform" }))
{
<p>
Find by name: @Html.TextBox("SearchString")
<button id="model-opener">Open dialog</button>
</p>
<div id="dialog-model" title="This is title">
<p>
@Html.TextBoxFor(item => item.FirstName, new { id = "ffirst" })<br />
@Html.TextBoxFor(item => item.LastName, new { id = "llast" })<br />
</p>
</div>
}
</body>
</html>
@section script
{
<script>
$(function () {
$("#dialog-model").dialog({
autoOpen: false,
height: 300,
width: 340,
model: true,
show: {
effect: "shake",
duration: 100
},
});
$("#model-opener").click(function (e) {
e.preventDefault();
var txtFirstName = $('#ffirst');
var txtLastName = $('#llast');
var txtSearch = $('#SearchString');
$.ajax({
url: '/popup/Index',
type: 'GET',
data: {
StudentId: txtSearch.val()
},
success: function (data) {
txtFirstName.val(data.FirstName); //HERE IS THE PROBLEM IN GETTING VALUE
txtLastName.val(data.LastName); //HERE IS THE PROBLEM IN GETTING VALUE
$("#dialog-model").dialog("open");
},
error: function () {
alert("Oh noes");
}
});
});
});
</script>
}
以下是我的控制器
public ActionResult Index(int? StudentId)
{
if (StudentId == null)
{
StudentId = 2;
return View();
}
using (var db = new StdContext())
{
Student std = new Student();
std = db.Students.Where(m => m.StudentId == StudentId).Single();
return View(std);
}
}
答案 0 :(得分:0)
您没有返回数据,而是返回视图:
return View(std);
如果您只想返回JavaScript代码要使用的Student
对象的数据,那么您可能只想将其作为JSON数据返回:
return Json(std);