How to pass dynamic value in @Url.Action?

前端 未结 3 447
盖世英雄少女心
盖世英雄少女心 2020-12-30 00:33

I have written following jquery in my partial view:

    $.ajax({
        type: \"POST\",
        url: \'@Url.Action(\"PostActionName\", \"ControllerName\")\'         


        
相关标签:
3条回答
  • 2020-12-30 01:13

    Have you tried something like this? I haven't tried it myself, but it should work.

    var dataToSend = "01";
    var url = '/controllerName/actionName/' + dataToSend;
    var actionName = ActionName();
    var controllerName = ControllerName();
    url.replace("actionName",actionName);
    url.replace("controllerName",controllerName);
    window.location = url;
    
    0 讨论(0)
  • 2020-12-30 01:15
       function functionName(var1, var2) {var link = '@Url.Action("MethodName", "Controller", new { id = "-1", name = "-2" })';
        link = link.replace("-1", var1);
        link = link.replace("-2", var2);}
    

    before, replace:

     html += "<a class='k-button k-button-icontext k-primary' href='" + link + "'><i class='fa fa-download'></i> Name Button</a>"
    
    0 讨论(0)
  • 2020-12-30 01:32

    I have functions to fetch invoking action and controller names, but not sure how I can pass them in @Url.Action

    Well, you could call those functions. For example if they are extension methods to the UrlHelper class:

    window.location = '@Url.Action(Url.MyFunction1(), Url.MyFunction2())'
    

    or if they are just static functions:

    window.location = '@Url.Action(SomeClass.MyFunction1(), SomeClass.MyFunction2())'
    

    If on the other hand the values that need to be passed are known only on the client you could do the following:

    var param = 'some dynamic value known on the client';
    var url = '@Url.Action("SomeAction", "SomeController", new { someParam = "__param__" })';
    window.location.href = url.replace('__param__', encodeURIComponent(param));
    

    UPDATE:

    It seems that you are just trying to fetch the current controller and action which could be achieved like that:

    @{
        string currentAction = Html.ViewContext.RouteData.GetRequiredString("action");
        string currentController = Html.ViewContext.RouteData.GetRequiredString("controller");
    }
    

    and then:

    window.location.href = '@Url.Action(currentAction, currentController)';
    
    0 讨论(0)
提交回复
热议问题