在我的appliaction中,我有一个控制器消息
public class MessageController : BaseController
{
...
}
BaseController是一个abstact类,包含一个FindUserForMessages方法。此方法必须位于此控制器中,因为此“BaseController”与3个类似Web应用程序中的父级一样使用,并包含所有应用程序的通用功能。
public abstract class BaseController : Controller
{
[Authorize]
[HttpPost]
[AcceptVerbs(HttpVerbs.Post)]
public JsonResult FindUser(string userName, int maxRecords)
{
try
{
return Json(new JsonResult()
{
IsError = false,
ErrorMessage = string.Empty,
Data = (from u in AccountModel.FindUser(userName, false).Take(maxRecords)
select new
{
UserName = u.UserName,
UserId = u.ProviderUserKey,
IsOnlien = u.IsOnline
})
});
}
catch (Exception ex)
{
...
}
}
}
我想将此方法用于JqueryUI AutoComplete小部件的源代码。我试图通过Ajax调用这个方法:
$("#txtQuickMessageSendTo").autocomplete({
source: function (request, response) {
$.ajax({
url: "/Message/FindUser",
data: {
userName: request.term,
maxRecords: 10
},
success: function (resultObj) {
if (resultObj.IsError) {
handleAjaxError(null, null, null, null, resultObj.ErrorMessage, null);
return;
}
else {
response($.map(data.Data, function (item) {
return {
label: item.UserName,
value: item.ProviderUserKey
}
}));
}
}
});
},
minLength: 2,
select: function (event, ui) {
//log(ui.item ? "Selected: " + ui.item.label : "Nothing selected, input was " + this.value);
},
open: function () {
$(this).removeClass("ui-corner-all").addClass("ui-corner-top");
},
close: function () {
$(this).removeClass("ui-corner-top").addClass("ui-corner-all");
}
});
我使用Fiddler2进行Web调试,并且在请求中都是参数(userName和maxRecords),但是服务器抛出错误:
Description: HTTP 404. The resource you are looking for (or one of its dependencies) could have been removed, had its name changed, or is temporarily unavailable. Please review the following URL and make sure that it is spelled correctly.
Requested URL: /Message/FindUserForMessages
参数没关系,但为什么我不能调用这个方法?
感谢
答案 0 :(得分:2)
1)您的错误消息显示您尝试访问FindUserForMessages
方法。但是代码中的方法是FindUser
!
2)此外,始终使用Html帮助方法获取操作方法的路径。所以替换
url: "/Message/FindUser",
与
url: "@Url.Action("FindUser","Message")",
3)默认情况下,ajax操作类型为GET
。您的操作方法使用[HttpPost]
atttribute进行修饰。所以要么从那里删除它,要么在你进行ajax调用时提及。还要确保您确实需要Authorize
属性来满足您的要求。
public JsonResult FindUser(string userName, int maxRecords)
{
return Json( new { YourJsonDemo="replace here" },
JsonRequestBehaviour.AllowGet);
}
或者在客户端进行说明它是POST
请求。
$.ajax({
url: "@Url.Action("FindUser","Message")",
type: 'POST',
//remaining code
答案 1 :(得分:0)
FindUser方法只接受帖子。删除[HttpPost]属性(您将需要使用JsonRequestBehavior.AllowGet - 未推荐),或确保jquery ajax选项指定type = post。