我刚刚注意到一种奇怪的行为,但我不太确定。我对 jQuery 和 AJAX 还很陌生。所以可能只是缺少一些基础知识。
在我的 MVC rzaor View 中,有一些 AJAX 操作链接,单击这些链接会呈现一个部分 View ,其中包含 div #StudentDetails 中的学生详细信息。
<div id="mainpage">
<h2>Registration Details</h2>
<ul>
@foreach(var item in Model)
{
<li>
@Ajax.ActionLink(item.Student.UserName, @*Text to be displayed *@
"GetUserDetails", @*Action Method Name*@
new { id = item.Student.StudentId },
new AjaxOptions
{
UpdateTargetId = "StudentDetails", @*DOM element ID to be updated *@
InsertionMode = InsertionMode.Replace,@*Replace the content of DOM element *@
HttpMethod = "GET" @*HTTP method *@,
OnComplete="RegisterClickHanders"
}
)
</li>
}
</ul>
<div id ="StudentDetails"></div>
<br />
<div id ="Add_Update_Details"></div>
</div>
渲染包含详细信息的 View 后,可以单击“编辑”或“添加”按钮,并渲染相应的部分 View 。
<script>
//Event Delegation
//$(function () {
//One can also use Event Delegation as stated above to handle dynamically added elements i.e. the elements
//that are added after the page is first loaded.
function RegisterClickHanders() {
var url = '@Url.Action("DisplayClickedView","Private")'; // Name of the action method you want to call and the name of the
//controller the action method resides
$('.editDetails').click(function () {
var btnvalue = $('.editDetails').attr("value");
var studentId = $('.editDetails').data("student-id");
$('#Add_Update_Details').load(url, { searchText: btnvalue, searchValue: studentId });
});
$('.addDetails').click(function () {
var btnvalue = $('.addDetails').attr("value");
$('#Add_Update_Details').load(url, { searchText: btnvalue });
});
}
</script>
他们恰好被击中一次,这是预期的。但是当我将 ajax 调用替换为:
$('.editDetails').click(function () {
var btnvalue = $('.editDetails').attr("value");
var studentId = $('.editDetails').data("student-id");
$.ajax({
type: 'POST',
url: url,
data: { searchText: btnvalue, searchValue: studentId },
success: function () {
$('#Add_Update_Details').load(url, { searchText: btnvalue, searchValue: studentId });
},
error: function (jqXHR, status, err) {//status is Error and the errorThrown is undefined
alert('Request Status : ' + jqXHR.status + ' has issued a status text of : ' + jqXHR.statusText);
}
});
});
$('.addDetails').click(function () {
var btnvalue = $('.addDetails').attr("value");
$.ajax({
type: 'POST',
url: url,
data: { searchText: btnvalue },
success: function () {
$('#Add_Update_Details').load(url, { searchText: btnvalue });
},
error: function (jqXHR, status, err) {//status is Error and the errorThrown is undefined
alert('Request Status : ' + jqXHR.status + ' has issued a status text of : ' + jqXHR.statusText);
}
});
});
按下任何按钮时 Controller 中的断点都会被击中两次。我缺少什么?或者这是故意的? AJAX 调用是否会导致性能下降?
最佳答案
.load
并且您的 ajax 调用都在调用您的 Controller 操作。
您应该返回一个 PartialView
并将其写入您的空 div
,如下所示:
$.ajax({
type: 'POST',
url: url,
data: { searchText: btnvalue, searchValue: studentId },
.success(function (result) {
$('#Add_Update_Details').html(result);
})
关于jquery - MVC Razor View 中的 AJAX 调用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35758468/