我希望实现的基本功能是在选择下拉列表项时更新表格的内容。当用户做出新选择并从数据库中检索新信息并重新填充表格时,这将更新。
还值得注意的是,我希望 .change() 使用的 DropDownListFor 不包含在 AjaxForm 中,而是出现在页面的其他地方(诚然以另一种形式)
为了实现这一点,我查看了这个问题:Rendering partial view dynamically in ASP.Net MVC3 Razor using Ajax call to Action这很好地完成了我想做的事情。
到目前为止,我有一个 Controller 方法可以处理为部分 View 填充自定义 View 模型:
[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; }
}
我用作局部 View 模型的强类型模型
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; }
}
它填充并返回的部分 View :
@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);
}
});
});
});
目前我已经克服了一些错误,目前我面临着:
“执行处理程序‘System.Web.Mvc.HttpHandlerUtil+ServerExecuteHttpHandlerAsyncWrapper’的子请求时出错。”
但是,我觉得我对整个问题的理解可能还不够。
感谢任何帮助!
最佳答案
此错误表示在呈现您的 subview 时出现异常。可能与您的数据有关,即。 NulLReferenceException
。
只需附加您的调试器并设置为在抛出异常时中断。
关于c# - 使用 Ajax 在 ASP.Net MVC3 Razor 中呈现局部 View ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8326278/