2
我剛剛注意到一個我不太確定的奇怪行爲。我對jQuery和AJAX很新穎。所以可能會錯過一些基本知識。AJAX調用MVC剃刀視圖
在我的MVC rzaor視圖中有一些AJAX動作鏈接,當點擊時渲染包含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>
在視圖獲取與細節渲染後,可以單擊編輯或添加按鈕,並呈現適當的部分視圖。
<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>
他們得到準確擊中一次,其目的。但是,當我將阿賈克斯調用替換爲:
$('.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);
}
});
});
按下任何按鈕後,控制器中的斷點會被擊中兩次。我錯過了什麼?或者這是打算? AJAX調用是否會導致性能下降?
非常感謝您的幫助。出於好奇,只有一個問題......那麼何時使用.load(因爲它會強制你指出的兩次調用)反對.html(result)? – StrugglingCoder
我對加載函數並不太熟悉,所以我不能真正說出它何時最適合使用它。點擊答案中的加載時,會有一個指向文檔的鏈接。在這種情況下,要理解的重要部分是,對'url'和load的ajax調用都調用了'DisplayClickedView'操作,這就是爲什麼你看到它碰到兩次中斷點。 – rogerdeuce