如何从控制器获取数据使用ajax请求查看 - asp.net mvc 4
问题描述:
我想从控制器获取数据使用ajax查看,但不成功。以下是我的代码这工作正常,但没有获取数据。请帮助并纠正我,如果我错过了我的代码中的东西。如何从控制器获取数据使用ajax请求查看 - asp.net mvc 4
以下是我的代码。
@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);
}
}
答
你没有返回数据,你就返回一个观点:
return View(std);
如果你只是想返回数据要使用JavaScript代码的Student
对象,那么您可能只想将其作为JSON数据返回:
return Json(std);
感谢您宝贵的答案,但如何获取数据作为JSON在AJAX?你能分享任何例子或代码吗?, – user3004110 2014-09-25 12:26:09
@ user3004110:嗯,想到的第一个例子是你的问题中的代码。成功处理程序中的'data'对象应该是JSON序列化的'Student'对象。 – David 2014-09-25 12:27:31
您需要控制器中的jsonResult方法 – 2014-09-25 13:29:40