我有自动完成功能。我的搜索方法位于HomeController中,但我想做一些更改。我创建了名为“Vacancy”的api控制器并在那里转移了搜索方法,但我无法使其工作:状态代码:404 Not Found(搜索方法甚至没有启动)。在转移我所做的所有更改后:
在视图中更改了源链接:
data-autocomplete="@Url.Action("Search", "Vacancy")"
更改了搜索方法:
public object Search(string term)
{
var vacancyHeaders =
new UnitOfWork().Repository<Vacancy>()
.Get()
.Where(v => v.Header.ToLower().Contains(term.ToLower()))
.Select(v => new { label = v.Header })
.Distinct()
.Take(10);
return vacancyHeaders;
}
请帮忙,为什么我的搜索方法无法启动? 下面是我没有api控制器的工作代码:
查看:
<form data-bind="submit: search">
<input data-bind="value: SearchArgument, valueUpdate: 'blur'" data-autocomplete="@Url.Action("Search", "Home")" class="form-text" name="search" size="32" maxlength="64" placeholder="Search"/>
<input type="submit" value="search" />
</form>
脚本
$(":input[data-autocomplete]").each(function() {
$(this).autocomplete({ source: $(this).attr("data-autocomplete")});
});
搜索方法
public ActionResult Search(string term)
{
var vacancyHeaders =
new UnitOfWork().Repository<Vacancy>()
.Get()
.Where(v => v.Header.ToLower().Contains(term.ToLower()))
.Select(v => new { label = v.Header })
.Distinct()
.Take(10);
return Json(vacancyHeaders, JsonRequestBehavior.AllowGet);
}
答案 0 :(得分:0)
如果要在Web API中使用自定义方法名称,则需要更改路由配置以允许它。
从Custom method names in ASP.NET Web API问题,这里有一个示例,说明如何配置WebApiConfig文件以包含额外的GET方法并支持常规REST方法:
config.Routes.MapHttpRoute("DefaultApiWithId", "Api/{controller}/{id}", new { id = RouteParameter.Optional }, new { id = @"\d+" });
config.Routes.MapHttpRoute("DefaultApiWithAction", "Api/{controller}/{action}");
config.Routes.MapHttpRoute("DefaultApiGet", "Api/{controller}", new { action = "Get" }, new { httpMethod = new HttpMethodConstraint(HttpMethod.Get) });
config.Routes.MapHttpRoute("DefaultApiPost", "Api/{controller}", new { action = "Post" }, new { httpMethod = new HttpMethodConstraint(HttpMethod.Post) });
现在,您可以将搜索方法设为以下内容:
public IQueryable GetAutocompleteResponse(string term = null)
{
var someStrings = new string[] { "vacancy1", "vacancy2" };
var model = someStrings.Select(c => new { label = c }).AsQueryable();
return model;
}
最后,我使用jQueryUI自动完成功能来测试它的代码:
<input type="search" name="searchTerm" data-autocomplete="@Url.Action("GetAutocompleteResponse", "Api/Vacancy")" />
<input type="submit" id="submitForm" value="Search By Name" />
@section scripts
{
<script>
var createAutocomplete = function () {
var self = $(this);
var options = {
source: self.attr("data-autocomplete")
};
self.autocomplete(options);
}
$(document).ready(function () {
$("input[data-autocomplete]").each(createAutocomplete);
});
</script>
}