我正在尝试使用 ajax 更新记录列表,在表中表示,其中每条记录作为 javascript 删除链接。如果我预加载表格,RemoveLink 工作正常,但是一旦通过 ajax 更新了 div“RecordListPartialView”,它就不再工作了。
我用 firebug 检查生成的 html 代码对于每一行都是正确的。看起来浏览器并不知道新代码,因此它不会触发 javascript 链接。
谁能解释一下这是怎么回事?
(1) 下面是查看代码:
$(".RemoveLink").click(function () {
var _id = $(this).attr("data-id");
var recordToDelete = { id: _id };
var json = $.toJSON(recordToDelete);
$.ajax({
url: '/MortagePayment/RemoveMortageRecord',
type: 'POST',
dataType: 'json',
data: json,
contentType: 'application/json; charset=utf-8',
success: function (data) {
$("#RecordListPartialView").empty();
$("#RecordListPartialView").html(data.Message);
}
});
});
$(".AddLink").click(function () {
var _year = $("#NewRecord_year").val();
var _month = $("#NewRecord_month").val();
var _mortageValue = $("#NewRecord_mortageValue").val();
var newRecord = { year: _year, month: _month, mortageValue: _mortageValue };
var json = $.toJSON(newRecord);
$.ajax({
url: '/MortagePayment/AddMortageRecord',
type: 'POST',
dataType: 'json',
data: json,
contentType: 'application/json; charset=utf-8',
success: function (data) {
$("#RecordListPartialView").empty();
$("#RecordListPartialView").html(data.Message);
$("#NewRecord_year").val(0);
$("#NewRecord_month").val(0);
$("#NewRecord_mortageValue").val(0);
}
});
});
<div id="RecordListPartialView">
@Html.Partial("MortageRecordList", Model.MortageRecordList)
</div>
(2) 局部 View
<table id="mortageRecordListTable">
<tr>
<th colspan=4>Current reductions</th>
</tr>
<tr>
<th>Year</th>
<th>Month</th>
<th>Value</th>
<th></th>
</tr>
@foreach (var item in Model) {
<tr id="row-@item.mortageRecordId">
<td>
@item.year
</td>
<td>
@item.month
</td>
<td>
@item.mortageValue
</td>
<td>
<p class="RemoveLink" data-id="@item.mortageRecordId">Remove</p>
</td>
</tr>
}
</table>
(3) 和 Controller :
[HttpPost]
public ActionResult AddMortageRecord(MortageRecord newRecord) {
var mortageRecordSet = MortageRecordSet.GetMortageSet(this.HttpContext);
if (ModelState.IsValid)
mortageRecordSet.AddMortageRecord(newRecord);
string partialViewHtml = RenderPartialViewToString("MortageRecordList", mortageRecordSet.GetMortageItems());
return Json(new { Success = true, Message = partialViewHtml });
}
[HttpPost]
public JsonResult RemoveMortageRecord(int id) {
var mortageRecordSet = MortageRecordSet.GetMortageSet(this.HttpContext);
mortageRecordSet.RemoveMortageRecord(id);
string partialViewHtml = RenderPartialViewToString("MortageRecordList", mortageRecordSet.GetMortageItems());
return Json(new { Sucess = true, Message = partialViewHtml });
}
最佳答案
如果我没理解错的话。
If I preload the table, the RemoveLink works fine, but once the div "RecordListPartialView" is updated via ajax, It no longer works.
使用 .live
更改您的 .click
事件>
$(".RemoveLink").live("click",function(){
//any click event code comes here
});
关于javascript - ASP.NET MVC 3 - Ajax 更新表 - 模型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8541138/