Generating an action URL in JavaScript for ASP.NET MVC

前端 未结 9 1116
梦毁少年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: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.

提交回复
热议问题