skip to Main Content

I define a variable in an IndexJson.cshtml view:

@section Scripts{
    @await Html.PartialAsync("_ValidationScriptsPartial")
    <script type="text/javascript">
        var area = "@ViewContext.RouteData.Values["area"].ToString()"
    </script>

If I leave the view and then revisit it then I get:

Identifier ‘area’ has already been declared

I have a left menu which I make an ajax call and then assign the HTML view in a container like:

function MenuClickItem(item) {
    $.ajax({
        type: "GET",
        url: item.dataset.area + "/" + item.dataset.controller + "/IndexJson",
        success: function (result) {
            $("#main-container").html(result);
        },
        error: function (res) {
            console.log("Error:" + res)
        }
    });
}

Why is this happening? Is there a way to avoid this?

2

Answers


  1. Chosen as BEST ANSWER

    if i empty my div every time I load the View then it works.

    function MenuClickItem(item) {
        $("#main-container").html("");
        $.ajax({
            type: "GET",
            url: item.dataset.area + "/" + item.dataset.controller + "/IndexJson",
            success: function (result) {
                $("#main-container").html(result);
            },
            error: function (res) {
                console.log("Error:" + res)
            }
        });
    }
    

  2. The problem is that the JavaScript in the partial view is being added and run in the same scope each time and then complains because the variable already exists.

    To get around this you should wrap the injected JS in an IIFE so that each partial views JS has it’s own scope.

        (function(){
            var area = "@ViewContext.RouteData.Values["area"].ToString()"
        })();
    

    This is good practice for most JavaScript code that you will likely write to keep it out of the global scope.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search