【问题标题】:Rendering partial view dynamically in ASP.Net MVC3 Razor using Ajax call to Action使用 Ajax 调用 Action 在 ASP.Net MVC3 Razor 中动态呈现部分视图
【发布时间】:2011-11-17 08:48:18
【问题描述】:

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

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

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

这是我目前所拥有的:

    @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. 如果这是正确的方法,我们该怎么做?特别是,我们如何只让属性表重新渲染?

  2. 如果有更好的方法实现上述,请指出。

谢谢

【问题讨论】:

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


    【解决方案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);
                }
            });
        });
    });
    

    【讨论】:

    • 谢谢。如何从下拉列表中获取所选项目的值?代替 form.serialize,也许我们可以传递类似 {'id': id} 的东西?
    • 更新:在 ajax 请求中,我在数据中给出了具体的方法 URL 和 id 值,(我也从 AjaxForm 恢复到 HtmlForm)并且一切正常。感谢上帝! ....谢谢达林。
    • 你能用工作代码更新这个问题吗?这正是我未能实现的目标:)
    猜你喜欢
    • 2012-01-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-03-12
    相关资源
    最近更新 更多