简体   繁体   中英

Using a flag variable to show/hide elements in ASP.NET MVC

I have a form as shown on the image having a dropdownlist, 2 divs and 2 buttons that are shown / hidden based on some situations on every page load (on initial load and after data retrieving, etc.). On the other hand I use a single variable called hasValue in the Controller and based on each situation I set this variable in the Controller and get this on Ajax success in the razor View. Then on page load I make the components visible hidden as shown below:

在此处输入图片说明

Controller:

public ActionResult DemoMethod() 
{
    //code omitted    
    if (...)
    {
        return Json(new { success = true, hasValue = true });
    }
    return Json(new { success = true, hasValue = false });                
}

View:

<a id="btn-save" href="javascript:toggleField(false);"> Save </a>


<script>
    var hasValue = false;

    $(function () {
        //I set hasValue property retrieved from Controller via Ajax on the razor page load and use whenever I need in the View
        toggleField(hasValue);
    });

    function toggleField(param) {
        $('#div1').css('display', !param ? 'block' : 'none');
        $('#div2').css('display', param ? 'block' : 'none');
        $('#btn1').css('display', param ? 'block' : 'none');
        $('#btn2').css('display', !param  ? 'block' : 'none');
    }

</script>

My problem is that. In some situations, the single variable hasValue is not enough. In this case should I use an extra parameter besides hasValue variable in each field above?

I am not sure if there is a better way or elegant solution for this kind of situations.

Any helps would be appreciated.

I think Jack means

function toggleField(param) {
        $('#div1').toggle(param);

        $('#div2').css('display', param ? 'block' : 'none');
        $('#btn1').css('display', param ? 'block' : 'none');
        $('#btn2').css('display', !param  ? 'block' : 'none');
    }

It's not helped by the image names not matching your code..

If you need to vars use two. Nothing wrong with that. Get it working then improve..

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM