我正在学习MVC3,我在部分视图中有以下@Ajax.Actionlink
,我想转换为使用ajax调用的jQuery方法,但是我有两个主要问题,我可以不太清楚:
@Ajax.ActionLink
会正确更新div。)以下是(我认为)相关代码的全部内容:
部分视图
@model ..snip../CustomerViewModel
<div id="updatedablediv">
<table class="customers" style="width: 50%">
<thead>
<tr>
<th>
Name
</th>
<th>
Actions
</th>
</tr>
</thead>
<tbody>
@if (Model != null)
{
foreach (Customer item in Model.Customers)
{
<tr id="customer-id-@item.CustomerID">
@Html.HiddenFor(i => item.CustomerID)
<td>
@Html.DisplayTextFor(i => item.Name)
</td>
<td>
@Ajax.ActionLink("Delete", "DeleteCustomer", "MyController", new { userID = Model.UserID, customerID = item.CustomerID },
new AjaxOptions() { UpdateTargetId = "updatedablediv", HttpMethod = "Get" }, new { @class = "standardbutton" })
</td>
</tr>
}
}
</tbody>
</table>
</div>
控制器操作
[HttpGet]
public PartialViewResult DeleteCustomer(int userID, int customerID)
{
try
{
//Delete code
}
catch (DataException)
{
ModelState.AddModelError("", "Unable to save changes.");
}
CustomerViewModel returnViewModel = new CustomerViewModel()
{
UserID = userID,
Customers = repository.Customers
};
return PartialView("CustomerPartial", returnViewModel);
}
我尝试过这样做,但我一直遇到上述问题。我的一个尝试是使用以下jQuery:
$("#buttonid").click(function(){
var loadUrl = $('#buttonid').attr('href');
$("#updatedablediv")
.html(DeleteCustomer)
.load(loadUrl, {userID: @model.UserID);
});
任何帮助我将此@Ajax.ActionLink
转换为jQuery的指针都将非常感激。
非常感谢,
更新HTML
这是我局部视图中<tr>
的实例的html。
<tr id="customer-id-1003">
<input id="item_CustomerID" name="item.CustomerID" type="hidden" value="1003" />
<td>
James
</td>
<td>
<a class="standardbutton" data-ajax="true" data-ajax-method="Get" data-ajax-mode="replace" data-ajax-update="#updatedablediv" href="/MyController/DeleteCustomer?userID=12&customerID=1003">Delete</a>
</td>
</tr>
答案 0 :(得分:1)
生成的链接的属性为您提供了正确执行AJAX请求所需的一切:
<a class="standardbutton"
data-ajax="true"
data-ajax-method="Get"
data-ajax-mode="replace"
data-ajax-update="#updatedablediv"
href="/MyController/DeleteCustomer?userID=12&customerID=1003"
>
所以我们这样做:
$('.standardbutton[data-ajax="true"]').click(function(e) {
e.preventDefault();
var $this = $(this);
$.ajax({
method: $this.data('ajaxMethod').toUpperCase(),
cache: false,
url: $this.attr('href'),
dataType: 'html',
success: function(resp) {
// this assumes that the data-ajax-mode is always "replace":
$($this.data('ajaxUpdate')).html(resp);
}
});
});