Generating an action URL in JavaScript for ASP.NET MVC

前端 未结 9 1111
梦毁少年i
梦毁少年i 2020-12-09 09:52

I\'m trying to redirect to another page by calling an action in controller with a specific parameter. I\'m trying to use this line:

window.open(\'<%= Url.         


        
相关标签:
9条回答
  • 2020-12-09 09:54

    The easiest way is to declare a javascript variable than concate your parameter value to the link.

      var url = '@Url.Action("Action","Controller")' + "/" + yourjavascriptvariable;
      <a href='" + url + "'> 
    
    0 讨论(0)
  • 2020-12-09 09:58

    Remember that everything between <% and %> is interpreted as C# code, so what you're actually doing is trying to evaluate the following line of C#:

    Url.Action("Report", "Survey", new { id = ' + selectedRow + ' } )
    

    C# thinks the single-quotes are surrounding a character literal, hence the error message you're getting (character literals can only contain a single character in C#)

    Perhaps you could generate the URL once in your page script - somewhere in your page HEAD, do this:

    var actionUrl =
        '<%= Url.Action("Report", "Survey", new { id = "PLACEHOLDER" } ) %>';
    

    That'll give you a Javascript string containing the URL you need, but with PLACEHOLDER instead of the number. Then set up your click handlers as:

    window.open(actionUrl.replace('PLACEHOLDER', selectedRow));
    

    i.e. when the handler runs, you find the PLACEHOLDER value in your pre-calculated URL, and replace it with the selected row.

    0 讨论(0)
  • 2020-12-09 10:03

    A way to do this that might be considered cleaner involves using the T4MVC T4 templates. You could then write the JavaScript inside your view like this:

    var reportUrl = '<%= Url.JavaScriptReplacableUrl(MVC.Survey.Report())%>';
    reportUrl = myUrl.replace('{' + MVC.Survey.ReportParams.id + '}', selectedRow);
    
    window.open(reportUrl);
    

    The advantage of this is that you get compile-time checking for the controller, action, and action parameter.

    0 讨论(0)
  • 2020-12-09 10:08

    One more thing that can be done, no so clean i guess:

    var url = "@Url.RouteUrl(new { area = string.Empty, controller = "Survey", action = "Report" })";
    var fullUrl = url  + '?id=' + selectedRow;
    
    0 讨论(0)
  • 2020-12-09 10:10

    Just if someone is still looking for this. The controller action can have normal parameters or a model object with these fields. MVC will bind the valus automatically.

     var url = '@Url.Action("Action", "Controller")';
     $.post(url, {
          YearId: $("#YearId").val(),
          LeaveTypeId:  $("#LeaveTypeId").val()
     }, function (data) {
          //Do what u like with result
     });
    
    0 讨论(0)
  • 2020-12-09 10:11

    You wont be able to do this, the URL.Action is a server side process so will parse before the clientside selectedRow is available. Israfel has the answer I would suggest.

    0 讨论(0)
提交回复
热议问题