Rendering partial view dynamically in ASP.Net MVC3 Razor using Ajax call to Action

杀马特。学长 韩版系。学妹 提交于 2019-12-24 07:06:35

问题


I'm trying to create a single page form to create a 'work item'. One of the properties is a drop down for 'work item type'.

Depending on the work item type, the user may need to provide additional information in a name-value-pair style attributes grid (property sheet).

I would like to dynamically render the property sheet as soon as a work item type is selected or changed. Once the user provides all information, he would click submit to create the 'work item'.

This is what I have so far:

    @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>
}

The AttributeData action in the controller simply renders the partial view:

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

}

Now I would like to hook this up to the drop-down-list's selection event so that the partial view re-renders in the above table cell at every selection change. I would like to pass in the selected value as id.

One way is to force the form to submit itself (and thus re-render).

  1. If that is the right approach, how do we go about it? Esp., how do we make only the property sheet to re-render?

  2. If there is a better way to achieve the above, please indicate.

Thanks


回答1:


You could subscribe to the .change() event of the dropdown and trigger an AJAX request:

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


来源:https://stackoverflow.com/questions/8164328/rendering-partial-view-dynamically-in-asp-net-mvc3-razor-using-ajax-call-to-acti

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!