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

时间:2011-11-17 08:48:19

标签: asp.net ajax asp.net-mvc-3 dynamic razor

我正在尝试创建单页表单来创建“工作项”。其中一个属性是“工作项类型”的下拉列表。

根据工作项类型,用户可能需要在名称 - 值对样式属性网格(属性表)中提供其他信息。

我想在选择或更改工作项类型后立即动态呈现属性表。一旦用户提供了所有信息,他就会点击提交以创建“工作项”。

这是我到目前为止所做的:

    @using (Ajax.BeginForm("AttributeData", new AjaxOptions() { UpdateTargetId="AttributeDataCell" }))
{

        <div style="float:left">

@{
    Html.RenderPartial("CreateWorkItemPartialView");
 }
 </div>     

<div id="AttributeDataCell" style="float:right">
    @Html.Action("AttributeData", new {id = 1})
</div>
}

控制器中的AttributeData操作只是呈现局部视图:

public ActionResult AttributeData(int id = 0)
{
    var attributes = _workItemDataService.ListWorkItemTypeAttributes(id);
    return PartialView("EditWorkItemAttributesPartialView", attributes);

}

现在我想把它连接到下拉列表的选择事件,以便部分视图在每次选择更改时在上面的表格单元格中重新呈现。我想将所选值传递为id。

一种方法是强制表单提交(然后重新呈现)。

  1. 如果这是正确的方法,我们该怎么做呢? Esp。,我们如何只重新制作属性表呢?

  2. 如果有更好的方法可以实现上述目标,请注明。

  3. 由于

1 个答案:

答案 0 :(得分:1)

您可以订阅下拉列表的.change()事件并触发AJAX请求:

$(function() {
    $('#Id_Of_Your_Drop_Down').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 = $('form');

        // 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:
                $('#AttributeDataCell').html(result);
            }
        });
    });
});