自定义Ajax帮助程序在MVC中未命中控制器
本文关键字:控制器 MVC Ajax 帮助程序 自定义 | 更新日期: 2023-09-27 18:29:30
我为搜索文本框找到了一个很好的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
,它有相同的选项,运行正常。
不要硬编码url(忘记在jobId
参数前附加/
):
Url = "JobCardView/UserApply"+jobId
尝试使用内置的框架工具来处理url(UrlHelper
):
Url = new UrlHelper(ajaxHelper.ViewContext.RequestContext).Action("UserApply", "JobCardView", jobId)
这样你就可以得到一个正确的网址:
data-ajax-url="JobCardView/UserApply/2"