C# 将变量作为参数传递给 javascript 中的 Url.Action

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/16835174/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-10 07:54:57  来源:igfitidea点击:

pass variable as parameter to Url.Action in javascript

c#asp.netasp.net-mvc-4razor

提问by Altaf Sami

I am passing parameters to @Url.Action like this:

我将参数传递给@Url.Action,如下所示:

function showHistory()
{

myId= $("#id").val();
    //alert(myId);
    actionDialog.load("@Url.Action("ActionHistoryAjax", new {id = myId, sort = "abc"})", function   () {
        actionDialog.dialog('open');
    });
}

But gives error "the name myId does not exist in the current context".

但给出错误“当前上下文中不存在名称 myId”。

How i can pass the variable?

我如何传递变量?

I solved this, this is the solution:

我解决了这个,这是解决方案:

function showHistory()
{

myId= $("#id").val();
//alert(myId);
actionDialog.load("@Url.Action("ActionHistoryAjax", new {id = "_Id", sort = "abc"})".replace("_Id", DeviceID), function   ()     {
 actionDialog.dialog('open');
});
}

采纳答案by Altaf Sami

I solved it by using this:

我用这个解决了它:

function showHistory()
{
    myId= $("#id").val();
    actionDialog.load("@Url.Action("ActionHistoryAjax", new {id = "_Id", sort = "abc"})".replace("_Id", DeviceID), function   ()     {
        actionDialog.dialog('open');
    });
}

回答by CodingIntrigue

You're mixing server-side and client-side code here. You can't pass a Javascript variable into the Url.Action method like that.

您在这里混合了服务器端和客户端代码。您不能像那样将 Javascript 变量传递到 Url.Action 方法中。

You would need to do something like:

您需要执行以下操作:

function showHistory()
{
    myId= $("#id").val();
    actionDialog.load("@Url.Action("ActionHistoryAjax", new { sort = "abc"})" + 
                      "&id=" + encodeURIComponent(myId), function   () {
        actionDialog.dialog('open');
    });
}

Or else load that ID from the server model.

或者从服务器模型加载该 ID。

回答by Khalid

old one
function showHistory()
{

  myId= $("#id").val();
  //alert(myId);
  actionDialog.load("@Url.Action("ActionHistoryAjax", new {id = myId, sort = "abc"})", 
  function   () {
    actionDialog.dialog('open');
  });
}

New one

新的一个

function showHistory()
{

 myId= $("#id").val();
 //alert(myId);
    actionDialog.load("@Url.Action("ActionHistoryAjax", new {id = "+ myId +", 
     sort =    "abc"})", function   () {
     actionDialog.dialog('open');
 });
}