【发布时间】:2012-01-09 17:00:26
【问题描述】:
我希望实现的基本功能是在选择下拉列表项时更新表格的内容。当用户做出新的选择并从数据库中检索新信息并重新填充表格时,这将更新。
还值得注意的是,我希望 .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>
最后是我几乎直接从达林的回答中提出的功能:
$(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'的子请求时出错。”
但是,我觉得我对整个问题的理解可能有所欠缺。
任何帮助表示赞赏!
【问题讨论】:
-
您应该添加包含相关操作方法的控制器定义。
-
@ChrisMarisic 我不明白为什么?我使用的唯一类变量是“_model”,它是我正在使用的存储库的服务层,那里没有问题。我误会你了吗?
-
@NickLarsen 恐怕我不知道。
-
@MattTolliday 在堆栈跟踪中,您会看到它说类似“内部堆栈跟踪”,或者如果您正在使用 Visual Studio 调试它,并在调试器中捕获异常,您可以检查异常,它有一个
InnerException属性。 -
@NickLarsen 这是一些非常有用的建议;在控制器上找不到公共操作方法“CompanyBillingBandDetails”是孤立的。 (它正在查看正确的控制器)。多么奇怪……
标签: c# asp.net-mvc-3 razor asp.net-ajax