我想更新一个记录列表与ajax,代表一个表,其中每个记录作为一个JavaScript删除链接。如果我预加载表,RemoveLink工作正常,但一旦div“RecordListPartialView”通过ajax更新,它不再有效。ASP.NET MVC 3 - 阿贾克斯更新表 - 型号
我用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)的局部视图
<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="[email protected]">
<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)和所述控制器:
[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 });
}
就是这样!那是什么魔法? – mugen 2011-12-16 23:32:51