Nalaka526
Nalaka526

Reputation: 11464

Can not access variable from @Url.Action

I have this Javascript in a ASP.Net MVC page

onComplete: function (id, fileName, responseJSON) {
    if (responseJSON.success) {
        $('#divImgs ul').append(
            $('<li>').append(
            $('<a>').attr('href', 
                '@Url.Action("DeleteFile", "Upload", new { id = fileName})').append(
            $('<img>').attr('src', responseJSON.filePath))
         ));
     }
 }

This gives Compilation error

The name 'fileName' does not exist in the current context

Why can't I access fileName variable within the @Url.Action?

Upvotes: 1

Views: 1927

Answers (2)

mccow002
mccow002

Reputation: 6914

This issue is that @Url.Action is resolved server side while filename is a javascript variable on the client side. You're best bet is something like this:

onComplete: function (id, fileName, responseJSON) {
    if (responseJSON.success) {
        $('#divImgs ul').append(
            $('<li>').append(
            $('<a>').attr('href', '@Url.Action("DeleteFile", "Upload", new { id = "' + filename + '" })').append(
            $('<img>').attr('src', responseJSON.filePath))
         ));
     }
}

There might be a better way to append the filename to the url, but the idea here is to render out the base url from the server, then modify it as needed with the javascript.

EDIT: I agree with haim77. You need to have the route be rendered server side instead of just appending on the client side in case the format of the route changes. But in this case, we need to inject some javascript. So just inject the variable into the route so it resolves to the right format, but also outputs javascript compatible code.

Upvotes: 3

haim770
haim770

Reputation: 49095

Because filename is a JavaScript variable that only exists in the client-side, while @Url.Action is executed (beforehand) in the server-side when the View renders itself.

To solve the problem, i usually do something like:

@object URL_ACTION_PLACEHOLDER = "__MYPLACEHOLDER__";

// ...

onComplete: function (id, fileName, responseJSON) {
    if (responseJSON.success) {
        var myActionUrl = '@Url.Action("DeleteFile", "Upload", new { id = URL_ACTION_PLACEHOLDER })';
        myActionUrl = myActionUrl.replace('@URL_ACTION_PLACEHOLDER', fileName);

        $('#divImgs ul').append(
            $('<li>').append(
            $('<a>').attr('href', myActionUrl).append(
            $('<img>').attr('src', responseJSON.filePath))
         ));
     }
 }

Upvotes: 2

Related Questions