steavy
steavy

Reputation: 1576

Javascript malfunction

can someone explain me why this script is not working?

<script type="text/javascript">
function destroy(ID) {
    if (confirm("Deleting is a very bad thing! Sure?")) 
    {
        location.href='@Url.Action("SomeAction", new { id = ID })'
        }
}

The error is: The name 'ID' does not exist in the current context, and occures here new { id = ID } If I just replace ID in this way: new { id = 3 } it works fine. What is the problem?

Upvotes: 0

Views: 109

Answers (1)

gdoron
gdoron

Reputation: 150253

You mix your Server code with the client code.

ID is a javascript variable- exist only on the client.
@Url.Action("SomeAction", server code, Exist only on the server.

You can't mix them!

You can do something like this:

function destroy(ID) {
    if (confirm("Deleting is a very bad thing! Sure?")){
        var url ='@Url.Action("SomeAction")';
        url += '/?id =' + ID;
        location.href = url;
    }
}

You have to remember all the @ stuff in the views are compiled and executed in the server and no longer exist in the client. tricky razor...

By the way, I would have change the confirm message...

Upvotes: 4

Related Questions