Generating an action URL in JavaScript for ASP.NET MVC

前端 未结 9 1112
梦毁少年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 10:14

    Could you do

    window.open('/report/survey/' + selectedRow);
    

    instead where selected row I assume is the id? The routing should pick this up fine.

    or use getJSON

    Perhaps you could use JSONResult instead. Wherever the window.open should be call a method instead i.e. OpenSurveyWindow(id);

    then add some jquery similar to below

    function OpenSurveyWindow(id){
          $.getJSON("/report/survey/" + id, null, function(data) {
              window.open(data);
         });
    }
    

    now in your controller

    public JsonResult Survey(int id)
    {
        return Json(GetMyUrlMethod(id));
    }
    

    That code isnt syntactically perfect but something along those lines should work

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

    I usually declare a javascript variable in the section to hold the root of my website.

    <%="<script type=\"text/javascript\">var rootPath = '"
        + Url.Content("~/") + "';</script>" %>
    

    To solve your problem I would simply do

    window.open(rootPath + "report/survey/" + selectedRow);
    
    0 讨论(0)
  • 2020-12-09 10:21

    If selectedRow is a client-side variable, it won't work. You have to use @Israfel implementation to link. This is because the server-side runs before the client-side variable even exists.

    If selectedRow is a server-side variable within the view, change to this:

    window.open('<%= Url.Action("Report", "Survey", new { id = selectedRow } ) %>');

    This is because the id will infer the selectedRow variable type, or you could convert to string with ToString() method (as long as it's not null).

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