使用Ajax在ASP.Net MVC3 Razor中渲染局部视图

我希望获得的基本function是在选择下拉列表项时更新表的内容。 当用户进行新选择并从数据库中检索新信息并重新填充表时,这将更新。

值得注意的是,我希望.change()使用的DropDownListFor不包含在AjaxForm中,而是出现在页面的其他地方(不可否认的是另一种forms)

为了达到这个目的,我看了一下这个问题: 在ASP.Net MVC3 Razor中动态渲染局部视图,使用Ajax调用Action ,它可以很好地按照我想做的方式进行。

到目前为止,我有一个控制器方法来处理为局部视图填充自定义视图模型:

[HttpPost] public ActionResult CompanyBillingBandDetails(int id = 0) { var viewModel = new BillingGroupDetailsViewModel(); var billingGroupBillingBands = _model.GetAllRecordsWhere(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 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   @Html.DisplayTextFor(x => x.RangeFrom)     @Html.DisplayTextFor(x => x.RangeTo)     @Html.DisplayTextFor(x => x.Charge)   

页面此部分的Razor代码:

   @using (Ajax.BeginForm("CompanyBillingBandDetails", new AjaxOptions() { UpdateTargetId = "details", id = "ajaxform" })) { 
@Html.Action("CompanyBillingBandDetails", new { id = 1 })
}
Range From Range To Charge

最后我从Darin的答案中直接解除了这个function:

 $(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); } }); }); }); 

目前我已经遇到了一些错误,目前我面临的是:

“执行处理程序’System.Web.Mvc.HttpHandlerUtil + ServerExecuteHttpHandlerAsyncWrapper’的子请求时出错。”

但是,我觉得我对这个问题的理解可能是缺乏的。

任何帮助赞赏!

此错误表示在呈现子视图时出现exception。 可能与您的数据有关的东西,即。 NulLReferenceException

只需附加调试器并设置为在抛出exception时中断。