使用Ajax的url操作参数

时间:2017-04-11 21:09:05

标签: javascript c# asp.net ajax asp.net-mvc

我正在尝试使用参数将数据从视图传递到控制器。 现在我正在经历一些困难。一旦我从表中选择一行并按下一个具有onclick方法的按钮到ShowTasks()

,我试图传递这些参数

C#控制器:

     [Route("/service/delivery/{id}/{shopdoccode}/{regdate}")]
     public ActionResult Delivery(string id, string shopdoccode, string regdate)
     {
        //do stuf
     }

用户点击按钮时的Javascript功能:

function ShowTasks() {
    //Dear Stackoverflow > This works, this is for selecting a row in the table
    var $selectedRow = $(".highlight");
    if ($selectedRow.length == 1) {
        var dcColumn = 0;
        var rdColumn = 1;
        var shopdoccodeColumn = 3;

        //assigning name to the colomn value 
        var id = $selectedRow[0].children[dcColumn].innerText.trim();
        var regdate = $selectedRow[0].children[rdColumn].innerText.trim();
        var shopdoccode = $selectedRow[0].children[shopdoccodeColumn].innerText.trim();

        //ajax 
        if (id && regdate && shopdoccode) {
            $.ajax({
                type: 'POST',
                url: '@Url.Action("service", "delivery" ,new { id = "id", shopdoccode = "shopdoccode", regdate = "regdate" })',
                data: { id, regdate, shopdoccode },
                success: function (data) {
                    if (data.success) {
                        console.log("Succes");
                    }

                },
                error: function (data) {
                    console.log("Error");
                }
            });
        }
    }
}

到目前为止我做了什么?坐了几个小时试图找到一种方法将参数提供给我的控制器,以便我可以调用SQL存储过程。 不幸的是,我不能简单地使用隐藏的形式。

这也非常有用: Url.Action parameters?

@sleeyuen enter image description here

3 个答案:

答案 0 :(得分:2)

在我看来,Url.Action的参数输入顺序错误。将其更改为:

url: '@Url.Action("delivery", "service", new { id = "id", shopdoccode = "shopdoccode", regdate = "regdate" })',

这是您想要的适当重载:

Action(String, String, Object),依次为actionName,controllerName和routeValues。

答案 1 :(得分:2)

使用Url.RouteUrl而不是Url.Action进行测试

答案 2 :(得分:2)

你不能* .js或* .html文件wrtie剃刀代码。

@Url.Action(string actionName,string controllerName,object routeValues)

以上代码只能用于* .cshtml文件。