Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MVC Partial View Returns Whole Page Instead of Just the Partial

I have the following partial view named "_transactions":

<div id="section-transactions" class="documentsanchor">
</div>
<div>
    <div class="row">
        <div class="col-lg-12">
            <div>
                <h4 class="company-headings">@ViewBag.SecSymbol Transactions</h4>
            </div>
        <div>
    </div>
</div>

I render it using

 @{Html.RenderAction("Transactions", "Company");}

and this is the Transactions method from the Company controller:

    public async Task<PartialViewResult> Transactions()
    {
        ViewBag.SecSymbol = "test";

        return PartialView("_transactions");
    }

It's on a page with other partial views.

This works fine. However, I have a button on the page that should get a new partial view and replace the current one. It makes an ajax call as follows

    $("#btn_transactions").click(function (e) {           
        var url = "Company/Transactions";
        $.ajax({
            url: url,
            success: function (result) {
                alert(result);
                $('#transTarget').html(result);
            },
            error: function () {
                alert("Error occured");
            }
        });
    })

The issue is that the whole page is returned in "result", that is, all partials as well as the layout, when all I want is the transactions partial. What am I doing wrong?

like image 411
Scott Avatar asked Dec 27 '17 16:12

Scott


People also ask

Can we return partial view in MVC?

In ASP.NET Core MVC, a controller's ViewResult is capable of returning either a view or a partial view. In Razor Pages, a PageModel can return a partial view represented as a PartialViewResult object. Referencing and rendering partial views is described in the Reference a partial view section.

How can you display partial view on the main page?

To create a partial view, right click on the Shared folder -> click Add -> click View.. to open the Add View popup, as shown below. You can create a partial view in any View folder. However, it is recommended to create all your partial views in the Shared folder so that they can be used in multiple views.

Can you just update a partial view instead of full page post?

The Partial View will be updated with the partial view returned from the child action. Jquery is still a legitimate way to update a partial. But technically, the answer to your question is YES.

How do I return multiple partial views from a controller?

You can only return one value from a function so you can't return multiple partials from one action method. If you are trying to return two models to one view, create a view model that contains both of the models that you want to send, and make your view's model the new ViewModel. E.g.


1 Answers

Add this code in partial view

@{
Layout=null;
}
like image 122
Uttam Suthar Avatar answered Sep 28 '22 10:09

Uttam Suthar