我正在尝试一个简单的任务,即根据输入的StudentId在文本框中显示学生姓名。我能够将学生姓名显示为来自jQuery - AJAX调用的警报但不在文本框中,我在这里缺少什么?
控制器:
[AcceptVerbs(HttpVerbs.Get | HttpVerbs.Post)]
public ActionResult DisplayStudentName(string id)
{
StudentDataContext db = new StudentDataContext();
var StudentName = (from p in db.vwStudents.Where(a => a.StudentNumber == id)
group p by p.StudentName into g
select g.Key).FirstOrDefault();
return Json(new { Name = StudentName });
}
jQuery的:
$(function () {
$('#submitButton').click(function () {
var link = '/StudentForm/DisplayStudentName';
$.ajax({
type: 'POST',
url: link,
data: { id: $('#id').val() },
dataType: 'json',
success: function (result) {
$("#StudentName").val(result.Name);
alert(result.Name);
},
error: function (result) {
alert("Failed")
}
});
});
});
查看:
<%@ Page Title="" Language="C#" MasterPageFile="~/Views/Shared/Site.Master" Inherits="System.Web.Mvc.ViewPage<dynamic>" %>
<asp:Content ID="Content1" ContentPlaceHolderID="TitleContent" runat="server">
Student Form
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server">
<div id="Data" style="text-align: left; height: 202px;">
Student Number:<input type="text" name="id" id="id"/><br />
Student Name:<input type="text" name="StudentName" id="StudentName"/><br />
<br />
<div id="Div1">
<button id="submitButton" name="submitButton" style="width:140px;">Display Short Name</button>
</div>
</div>
</asp:Content>
同样,我可以在警告窗口中显示学生姓名,但不能在文本框中显示,我错过了什么吗?
提前致谢
答案 0 :(得分:3)
您需要阻止提交按钮的默认行为。您可以使用jQuery preventDefault函数来执行此操作,
$(function () {
$('#submitButton').click(function (e) {
e.preventDefault(); //prevent default behaviour
var link = '/StudentForm/DisplayStudentName';
$.ajax({
type: 'POST',
url: link,
data: { id: $('#id').val() },
dataType: 'json',
success: function (result) {
$("#StudentName").val(result.Name);
},
error: function (result) {
alert("Failed")
}
});
});
})
调用preventDefault
方法时,不会触发事件的默认操作。因此,在这种情况下,表单提交不会发生(因此页面不会重新加载)。