Question

I have the following script , that is being used inside multiple views:-

 $("#ChoiceTag, #ChoiceName").each(function () {
            $(this).change(function () {
                if ($("#ChoiceName").prop("checked")) {
                    $.getJSON("@Url.Content("~/Firewall/LoadCSName")",
                    function (CSData) {
                        var select = $("#GeneralCSID");
                        select.empty();
                        select.append($('<option/>', {
                            value: "",
                            text: "Select Name..."
                        }));
                        $.each(CSData, function (index, itemData) {

                            select.append($('<option/>', {
                                value: itemData.Value,
                                text: itemData.Text
                            }));
                            select.val('@Model.CSIT360ID');
                    });
                });
            }

the script is exactly the same for all the views except for the controller name inside the following statement:-

$.getJSON("@Url.Content("~/Firewall/LoadCSName")",

so i am looking to move the above script and add it inside a separate .js file, and then reference this script , but i have the following two question:-

  1. if i move the script to the script folder i need to dynamically reference the current controller name to build the URL, so is this possible

  2. can i still reference the viewbag as i am currently doing .. Thanks

Was it helpful?

Solution

If you move your Javascript into an external file you can't use your Razor syntax. Therefore, @Url.Content("~/Firewall/LoadCSName") will not resolve.

To overcome this add this to your view

<script type="text/javascript"> var AppPath = '@Url.Content("~/")'</script>

and reference it in your script like this

$.getJSON(AppPath + "Controller/Action")

Regarding the viewbag. Just put the viewbags value in a variable as shown above and your external file can reference it.

Hope this helps

Update

<html lang="en" xmlns="http://www.w3.org/1999/xhtml">
<head>
    <meta charset="utf-8" />
    <title></title>
</head>
<body>


    <script type="text/javascript">
        var AppPath = '@Url.Content("~/")';
        var SomeValue = '@Model.CSIT360ID';
        var ControllerName = "Firewall/LoadCSName";
    </script>
    <!--Move this to an external File-->
    <script type="text/javascript">

        $("#ChoiceTag, #ChoiceName").each(function () {
            $(this).change(function() {
                if ($("#ChoiceName").prop("checked")) {

                    $.getJSON(AppPath + ViewBagValue), function(CSData) {
                            var select = $("#GeneralCSID");
                            select.empty();
                            select.append($('<option/>', {
                                value: "",
                                text: "Select Name..."
                            }));

                            $.each(CSData, function(index, itemData) {

                                select.append($('<option/>', {
                                    value: itemData.Value,
                                    text: itemData.Text
                                }));

                                select.val(SomeValue);
                            });
                            //end each

                    });
                }
            });

    </script>

</body>
</html>

Update 2

This is how you could reference the controller in the url.content

<script type="text/javascript">

    var AppPath = '@Url.Content("~/" + HttpContext.Current.Request.RequestContext.RouteData.Values["controller"])'
</script>

OTHER TIPS

you can get the controller name this way:

   @{
string controllerName = HttpContext.Current.Request.RequestContext.RouteData.Values["controller"].ToString();
}

To access controller name from view use

@{
    ViewContext.RouteData.Values["controller"].ToString();
}

To access controller instance one can use as follow

@{
    (HomeController)ViewContext.Controller
}

One (slightly hacky) to make the current controller name accessible to JS would be to burn it into a global or namespaced variable assignment in the layout.

<script>
var app = window.app || {}

app.currentController = "@HttpContext.Current.Request.RequestContext.RouteData.Values["controller"].ToString().toLower()";

</script>

Alternatively, a common way I work is to add classnames of the current controller and action to the body tag, to assist in DOM based routing in any javascript.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top