Ajax.ActionLink没有调用控制器动作

时间:2012-02-22 19:31:53

标签: c# asp.net asp.net-mvc-3 razor routing

我正在显示文件列表并允许用户从列表中删除。删除按钮对控制器执行ajax调用以运行“删除”操作。但是,永远不会调用删除操作。我正在获取AjaxOptions中定义的确认警报。为了它的价值,我使用WebForms引擎工作并将其移至Razor。这也是我第一次使用Area。如果我直接调用Delete操作,它会起作用。这是路由问题吗?

这是

背后的代码
  public EmptyResult Delete(string fileName)
    {
        if (fileName.IsNullOrEmpty()) return null;
        var model = new Models.BenefitBookletModel();
        model.DeleteBooklet(fileName);
        return null;
    }

这是标记

    @Ajax.ActionLink("test", "Delete", new { fileName = item.FileName }, new AjaxOptions
                                                                                 {
Confirm = "Are you sure you want to delete " + item.FileName + "?",
OnComplete = "function(){deleteComplete('" + item.jsReferenceableFileName + "')}",
HttpMethod = "DELETE",
OnFailure = "function(){alert('Could not delete file');}"
              }, new { @class = "DeleteButton" }
                                                                             )

这是我的RegisterRoutes

        routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
        routes.MapRoute("SubscriberAll","subscriber/{id}",new { controller = "Subscriber", action = "ShowAll" },new { id = @"\d+" } );
        routes.MapRoute("Default", "{controller}/{action}/{id}", new { controller = "Home", action = "Index", id = UrlParameter.Optional });

来自地区注册的路线

context.MapRoute("Marketing_default","Marketing/{controller}/{action}/{id}",new { action = "Index", id = UrlParameter.Optional }

这是生成的标记

<a href="/Marketing/BenefitBooklet/Delete?fileName=MyFileName.pdf" data-ajax-method="GET" data-ajax-failure="function(){alert('Could not delete file');}" data-ajax-confirm="Are you sure you want to delete MyFileName.pdf?" data-ajax-complete="function(){deleteComplete('MyFileName.pdf')}" data-ajax="true" class="DeleteButton"> </a>

2 个答案:

答案 0 :(得分:4)

您应该将函数名称指定为相应AjaxOptions属性的值。添加script部分:

<script type="text/javascript">
    function OnFailure(request, error) {
        alert('Could not delete file');
    }
    function OnComplete(request, error) {
        alert('Delete complete');
    }
</script>
在您的视图中

并在'AjaxOptions'中更改OnFailureOnComplete

OnFailure = "OnFailure"
OnComplete= "OnComplete"

答案 1 :(得分:1)

您正在将Action Link的HttpMethod定义为DELETE,但您的方法可能只接受GET。尝试使用删除操作动词进行装饰。

[HttpDelete]
public EmptyResult Delete(string fileName)