Raza Ali
Raza Ali

Reputation: 595

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

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

Upvotes: 1

Views: 8307

Answers (1)

Darin Dimitrov
Darin Dimitrov

Reputation: 1039588

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

Upvotes: 1

Related Questions