user2083386
user2083386

Reputation: 135

Hide Button based on the result in Partial view MVC

I have a parent.cshtml page where it renders a partial view called _child.cshtml. This _child.cshtml contains a datatable and displays the data in the grid. Whenever this datatable doesn't contain, I need to hide the button which is in parent.cshtml. Please help me out how can I achieve this.

I have tried the below so far in parent view

jQuery.ajax(type: "POST",
        url: "{ChilePartialView}",
        data: { data },
        success: function (response) 
        {
            if (!response.Product.Count > 0) {
                jQuery("formSaveButton").hide();
            }
        });

Also I have tried the below as well:

jQuery(document).ready(function () {
    $.get('/ControllerName/ActionMethodName', function (data) {
        if (!data.Products.Count > 0) {
            $("formSaveButton").hide();
        }
    });

But none of them worked

Upvotes: 0

Views: 508

Answers (1)

Serega
Serega

Reputation: 650

You should understand that actions of your controller basically return just html markup (if only you don't explicitly return other ActionResult, for example JSON). You can't work with this markup in a way like

if (!data.Products.Count > 0)

Any JS script you insert to the child view will be just rendered as part of your html page and can hide any element from the page - it doesn't matter if hidden element is in parent or child view on the server side. Therefore you can just insert to your child view an inline script that will hide selected element in $(document).ready listener.

A bit more accurate solution uses sections (see for example this artice) and allows to output all inline scripts in one place (usually before closing body tag).

Upvotes: 1

Related Questions