简体   繁体   中英

MVC jquery call action controller not working

I have some jquery shown below required to run my mvc action and return the view.

   $("#workspaces").change(function () {
    var workspaceId = $('#workspaces').val();
    var url = '@Url.Action("SingleWorkspace", "Workspaces", new { id = workspaceId })';
    $.ajax({
        url: url,
        success: function () { alert("true"); }
    });
});

Basically the first issue i have is that it does not recognise the workspaceId within the url action if though the var is declared above it.

Secondly this is within a partial view as it is a dropdown menu. So by calling the url.action above how would it load the page?

any help would be appreciated

cheers

   var workspaceId = $('#workspaces').val();  
   var url = '@Url.Action("SingleWorkspace", "Workspaces", new { id = workspaceId })';

Url.Action - is server code (ASP.NET MVC helper) and workspaceId selected on client, that's why url can't be created here.

Firstly, the workspaceId is defined on the client, whereas the @Url.Action is run on the server so the variable doesn't exist at the point that the @Url.Action code executes. You want to send the workSpaceId as the data property of the jQuery ajax call instead or append the workspaceId to the url javascript variable instead on the client.

Secondly, if the action returns a partial view for example, then the jQuery success handler will receive an html string which you can inject into an element such as a div .

You can not do like that in javascript. What you can do is to get the path to SingleWorkSpace action method and append the workspaceId to that.

var url = "@Url.Action("SingleWorkspace", "Workspaces")/"+workspaceId;

or

var url = "@Url.Action("SingleWorkspace", "Workspaces")?id="+workspaceId;

You could use the following:

var workspaceId = $('#workspaces').val();
var url = '@Url.Action("SingleWorkspace", "Workspaces", new { id = "__id__" })'
    .replace('__id__', workspaceId);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM