Search code examples
javascripthtmlasp.net-mvcnoscript

How to determine if JavaScript is enabled through MVC


I have a View which calls the function 'Versions' on click of a href, which normally returns a 'Version.cshtml'. I modified that Controllerfunction: If i click on that link and JavaScript is enabled, it starts an ajax call which returns a JSON-result. It modifies the DOM so the page won't reload. Now my problem is to differentiate when JavaScript is enabled or not - If enabled, it should return the JSON result; if disabled it should return the 'Version.cshtml'. When I inspect the element, we have already a class called 'nojs-noborder' when JS is disabled. But how can i get that value through the controller without JS so I can fill the bool 'isJavaScriptenabled'?

Controller function looks like this:

   if (isJavaScriptEnabled)
        {

            var tocstr = ControllerContext.RenderView(PartialView("Versiontoc", model));
            var middlestr = ControllerContext.RenderView(PartialView("Versionmiddle", model));
            var result = new JsonResult
            {
                Data = new { tocstr, middlestr },
                JsonRequestBehavior = JsonRequestBehavior.AllowGet,
                MaxJsonLength = MaxValue
            };

            return result;
        }
        return View("Version", model);

The class in the inspected element:

<div class="nojs-noborder" id="contentwrapper">


Solution

  • It's unclear from your answer whether you have done this but you need to update your view to make an AJAX request or follow the anchor tag depending on whether JavaScript is enabled or not.

    Then, in your controller, you don't need to determine if JavaScript is enabled in the browser, but rather whether the request is an AJAX request. If it is, return JSON else return the view.

    Most JavaScript libraries will append the X-Requested-With header with a value of XMLHttpRequest. You can check for the existence of this header.

    I'm unsure what version of MVC you are using but you could use the built in Request.IsAjaxRequest() to determine this.

    Your ActionMethod then becomes:

    if (Request.IsAjaxRequest())
    {
        var tocstr = ControllerContext.RenderView(PartialView("Versiontoc", model));
        var middlestr = ControllerContext.RenderView(PartialView("Versionmiddle", model));
        var result = new JsonResult
        {
            Data = new { tocstr, middlestr },
            JsonRequestBehavior = JsonRequestBehavior.AllowGet,
            MaxJsonLength = MaxValue
        };
    
        return result;
    }
    return View("Version", model);
    

    If this method isn't available you could roll your own based on this answer