brinch
brinch

Reputation: 2614

How to return two partial views from controller as html?

I call my MVC controller action via Ajax, and want the action to return two partial views. Both partial views should be returned as html.

This is how I call via ajax

    $.ajax({
        url: '/SomeController/GetContent',
        type: 'GET',
        dataType: "html",
        success: function (d, status, xhr) {
            $('#partial1') = d.?
            $('#partial2') = d.?
        },
        error: function (req, status, errorObj) {
            alert('error');
        }
    });

I tried something like this for the controller action:

    public PartialViewResult[] GetContent()
    {
        PartialViewResult[] pvs = new PartialViewResult[2];

        pvs[0] = PartialView("Partial1", null);
        pvs[1] = PartialView("Partial2", null);

        return pvs;
    }

It works if I simply return one partial view (not returning as an array), but for two I just get an empty array returned in the ajax success. Any ideas how to solve this?

Upvotes: 0

Views: 4835

Answers (2)

nikudale
nikudale

Reputation: 417

I am not sure what you will be going to achieve but you are breaking basic binding of partial view and binding. are those both partial views having same one functionality but separate info then put in single partial view or if you have different functionality with separate view then bind with 2 ajax call. Alternate way you can use latest features of MVC6 viewcomponent http://www.asp.net/vnext/overview/aspnet-vnext/vc or AngularJS state binding.

Upvotes: 0

user3559349
user3559349

Reputation:

Create a single view that returns both partials

/Views/YourController/GetContent.cshtml

@Html.Partial("Partial1")
@Html.Partial("Partial2")

and change the method to

public PartialViewResult GetContent()
{
    return PartialView();
}

However if you need control over where each partial is placed in the view where you calling this method from, then you will need 2 separate methods and 2 separate ajax calls.

Upvotes: 1

Related Questions