自定义Ajax帮助程序没有命中MVC中的控制器

时间:2016-01-07 11:58:46

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

我为搜索文本框找到了一个很好的exemple Ajax助手,它看起来像这样:

public static MvcHtmlString Textbox(this AjaxHelper ajaxHelper, string name, 
    AjaxOptions ajaxOptions, object htmlAttributes)
{
    var tag = new TagBuilder("input");
    tag.MergeAttribute("name", name);
    tag.MergeAttribute("type", "text");

    tag.MergeAttributes(HtmlHelper.AnonymousObjectToHtmlAttributes(htmlAttributes));
    tag.MergeAttributes((ajaxOptions ?? new AjaxOptions()).ToUnobtrusiveHtmlAttributes());

    return MvcHtmlString.Create(tag.ToString(TagRenderMode.Normal));
}

从这个例子开始,我试图制作一个自定义的“AjaxButton”,到现在为止我有这个帮手:

public static MvcHtmlString AjaxButton(this AjaxHelper ajaxHelper, int jobId, bool apply)
{
    var myAjaxOptions = new AjaxOptions()
    {
        Url = "JobCardView/UserApply"+jobId,
        HttpMethod = "post",
        InsertionMode = InsertionMode.Replace,
        UpdateTargetId = "userInfo",
        OnSuccess = "CallBackCardView"
    };

    var tag = new TagBuilder("button");

    var color = apply ? "warning" : "primary";

    tag.MergeAttribute("class", "btn btn-"+color);
    tag.MergeAttribute("data-dismiss", "modal");

    var text = apply ? "Not Interested" : "Interested";

    tag.SetInnerText(text);


    tag.MergeAttributes((myAjaxOptions).ToUnobtrusiveHtmlAttributes());

    return MvcHtmlString.Create(tag.ToString(TagRenderMode.Normal));
}

呈现以下Html:

    <button 
class="btn btn-warning" 
data-ajax="true" 
data-ajax-method="post" 
data-ajax-mode="replace" 
data-ajax-success="CallBackCardView" 
data-ajax-update="#userInfo" 
data-ajax-url="JobCardView/UserApply2" 
data-dismiss="modal">
Not Interested
</button>

如何在此帮助程序中提供Url以便按预期运行?

我有Ajax.ActionLink,它有相同的选项,运行正常。

1 个答案:

答案 0 :(得分:3)

而不是对您的网址进行硬编码(并忘记在/参数前面添加jobId):

Url = "JobCardView/UserApply"+jobId

尝试使用内置的框架工具来处理网址(UrlHelper):

Url = new UrlHelper(ajaxHelper.ViewContext.RequestContext).Action("UserApply", "JobCardView", jobId)

以便您获得正确的网址:

data-ajax-url="JobCardView/UserApply/2"