Html.ActionLink没有以我想要的格式形成链接

时间:2013-06-03 21:13:12

标签: c# asp.net-mvc

快速新手问题。我不知道为什么我的Html.ActionLink会在“查看来源”

中转换为此内容
<a href="/Customer/CustomerSave?custid=1104">Save</a>

我的Html助手看起来像这样:

<%: Html.ActionLink("Save", "CustomerSave","Customer",new {custid = 101 })%> 

我在尝试联系我的控制器时收到“资源未找到”错误:

[HttpPost]
public ActionResult CustomerSave(int custid)
{
........
}

显然锚没有很好地形成。我已阅读其他帖子并尝试了其他选项,但我不完全了解发生了什么。我想要做的就是点击我的客户控制器中的操作(“CustomerSave”)。

我做错了什么?

3 个答案:

答案 0 :(得分:3)

将您的CustomerSave更改为HTTPGet或删除HTTPPost。

[HttpPost] //<-- Here
public ActionResult CustomerSave(int custid)
{
........
}

您收到错误是因为当您的操作标记了HTTPPost属性时,ActionLink将变为HttpGet。如果您想将其设为帖子,可以尝试通过单击链接向您的操作发出Ajax POST请求。默认操作URl链接点击将执行GET请求。

试试这种方式

       @Ajax.ActionLink("Save", 
             "CustomerSave",
            "Customer",
             new {custid = 101 },
            new AjaxOptions {
                HttpMethod = "POST",
                OnSuccess = "saveCustomer"
        }) ;

和JS

 function saveCustomer(response, status, data) {

       // Here you get any response
    }

或者您可以在customerSave链接的点击处理程序中使用普通Jquery Ajax POST

答案 1 :(得分:0)

在Global.asax.cs文件中,RegisterRoutes方法应如下所示:

public static void RegisterRoutes(RouteCollection routes)
    {
        routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
        routes.MapRoute(
            name: "Default",
            url: "{controller}/{action}/{id}",
            defaults: new { controller = "Customer", action = "CustomerSave", custid = UrlParameter.Optional }
        );
       }

并且您的控制器方法应该具有相同的参数custid。

答案 2 :(得分:0)

Html.ActionLink创建一个锚标记,这些只是GET。

尝试使用Ajax.ActionLink:

<%: Ajax.ActionLink("Save", "CustomerSave","Customer",new {custid = 101 }, new AjaxOptions{ HttpMethod="Post"})%>