我希望实现的基本功能是,当选择下拉列表项时,更新表格内容。这将在用户进行新选择时更新,并从数据库检索新信息并重新填充表格。
值得注意的是,我想要.change()与之配合使用的DropDownListFor不包含在AjaxForm中,而是出现在页面的其他位置(诚然,在另一个表单中)。
为了实现这个目标,我查看了这个问题:Rendering partial view dynamically in ASP.Net MVC3 Razor using Ajax call to Action,它做到了部分我想要做的事情。
到目前为止,我有一个控制器方法来处理为局部视图填充定制的视图模型:
我正在使用的强类型模型作为部分视图的模型。
这部分页面的Razor代码如下:
值得注意的是,我想要.change()与之配合使用的DropDownListFor不包含在AjaxForm中,而是出现在页面的其他位置(诚然,在另一个表单中)。
为了实现这个目标,我查看了这个问题:Rendering partial view dynamically in ASP.Net MVC3 Razor using Ajax call to Action,它做到了部分我想要做的事情。
到目前为止,我有一个控制器方法来处理为局部视图填充定制的视图模型:
[HttpPost]
public ActionResult CompanyBillingBandDetails(int id = 0)
{
var viewModel = new BillingGroupDetailsViewModel();
var billingGroupBillingBands =
_model.GetAllRecordsWhere<BillingGroupBillingBand>(x => x.BillingGroupId == id).ToList();
foreach (var band in billingGroupBillingBands)
{
viewModel.BillingBands.Add(band.BillingBand);
}
return PartialView("BillingGroupDetailsPartial", viewModel);
}
我希望每次调用时填充的ViewModel:
public class BillingGroupDetailsViewModel
{
public List<BillingBand> BillingBands { get; set; }
}
我正在使用的强类型模型作为部分视图的模型。
public class BillingBandsObject
{
public int BillingBandId { get; set; }
public int RangeFrom { get; set; }
public int RangeTo { get; set; }
public Decimal Charge { get; set; }
public int BillingTypeId { get; set; }
public bool Delete { get; set; }
}
它填充并返回的部分视图:
@model xxx.xxx.DTO.Objects.BillingBandsObject
<tr>
<td>
@Html.DisplayTextFor(x => x.RangeFrom)
</td>
</tr>
<tr>
<td>
@Html.DisplayTextFor(x => x.RangeTo)
</td>
</tr>
<tr>
<td>
@Html.DisplayTextFor(x => x.Charge)
</td>
</tr>
这部分页面的Razor代码如下:
<table>
<thead>
<tr>
<th>
Range From
</th>
<th>
Range To
</th>
<th>
Charge
</th>
</tr>
</thead>
<tbody>
@using (Ajax.BeginForm("CompanyBillingBandDetails", new AjaxOptions() { UpdateTargetId = "details", id = "ajaxform" }))
{
<div id="details">
@Html.Action("CompanyBillingBandDetails", new { id = 1 })
</div>
}
</tbody>
</table>
最后,我几乎直接从Darin的答案中提取了以下函数:
$(function () {
$('#billinggrouplist').change(function () {
// This event will be triggered when the dropdown list selection changes
// We start by fetching the form element. Note that if you have
// multiple forms on the page it would be better to provide it
// an unique id in the Ajax.BeginForm helper and then use id selector:
var form = $('#ajaxform');
// finally we send the AJAX request:
$.ajax({
url: form.attr('action'),
type: form.attr('method'),
data: form.serialize(),
success: function (result) {
// The AJAX request succeeded and the result variable
// will contain the partial HTML returned by the action
// we inject it into the div:
$('#details').html(result);
}
});
});
});
目前我已经解决了一些错误,但是现在面临的问题是:
"Error executing child request for handler 'System.Web.Mvc.HttpHandlerUtil+ServerExecuteHttpHandlerAsyncWrapper'."
然而,我感觉我对这个问题的整体理解可能还不够清楚。
非常感谢任何帮助!