Search code examples
javascriptc#asp.net-mvcasp.net-corerazor

How to use a bool value set in CSHTML file which is set in JS File


A bool value based on some condition in is present in sample.js file.

bool validation = false

this bool has to be utilized in a cshtml file to display different options within a list, below is the sample code for list

 <li> <a href="javascript:void(0)" title="Test" id="EditTest">Edit Test</a> </li>

By the utilization of validation(bool) is sample.js file, the different set of list is to be displayed which is put up in test.cshtml

if(validation){ 
    <li> <a href="javascript:void(0)" title="Test" id="EditTest">Freeze Test</a></li> }  
else{ 
    <li> <a href="javascript:void(0)" title="Test" id="EditTest">Edit Test</a></li>}

Is this possible by any means, please guide me on this. Thank you


Solution

  • How to use a bool value set in CSHTML file which is set in JS File

    Well, based on your scenario and description, its depends how you are preserving your validation value within your javascrip file.

    We cannot manipulate cshtml value after its been rendered, because cshtml has render from server-side but javascript lives in browser side. This is why we cannot manipulate directly cshtml once they rendered.

    But one thing you can do is, let your variable render from server-side and then based on the that value you can manipulate your DOM, it can be the good option considering this scenario.

    This can be done using either ways. Using DOM manipulation, server-side rendering or even using hidden input field.

    The most easiest way to using server-side rendering. You can do that as following:

    Controller:

    public IActionResult Index()
    {
        Random random = new Random();
        bool validation = random.Next(2) == 0;
        ViewBag.Validation = validation;
        return View();
    }
    

    View:

    @if (ViewBag.Validation)
    {
        <li><a href="javascript:void(0)" title="Test" id="EditTest">Freeze Test</a></li>
    }
    else
    {
        <li><a href="javascript:void(0)" title="Test" id="EditTest">Edit Test</a></li>
    }
    

    Output:

    enter image description here

    Note: You can also use fo TempData[""] for that. However, to fit with your requirement, you can also try other strategies as well which I've pointed dout above.