我正在尝试对使用 HttpPost 方法的 Controller 进行 ajax 调用
AJAX 调用
$(document).ready(function () {
$('#contactDiv ').click(function() {
var number = $(this).find('.ContactNumber').text();
var dataJson = {"contactNumber": number};
// var dataJson = {"contactNumber": number };
$.ajax({
type: "POST",
url: "../contactWeb/messages",
data: JSON.stringify(dataJson),
//data: dataJson,
contentType: "application/json",
cache: false,
success: function (msg) {
//msg for success and error.....
// alert(msg);
return true;
}
});
location.href = '@Url.Action("messages")';
});
});
Controller
[HttpPost] [允许匿名] 公共(public) ActionResult 消息(字符串 contactNumber) { //根据联系方式返回特定用户的应用消息 Int64 userID = Convert.ToInt64(Session["userId"]); 尝试 { 列表 messagesModel = new List(); IMessages MessageObject = new MessagesBLO();
messagesModel = MessageObject.GetAllMessagesWeb(userID , contactNumber);
ViewData["Data"] = messagesModel;
}
catch (Exception e)
{
}
return View();
// string msg = "Error while Uploading....";
//return Json(msg, JsonRequestBehavior.AllowGet);
}
[HttpGet]
public ActionResult messages()
{
return View();
// string msg = "Error while Uploading....";
//return Json(msg, JsonRequestBehavior.AllowGet);
}
查看“消息”
@model OyeAPI.Models.PhoneMessages
@{
ViewBag.Title = "messages";
List<Model.MessagesModel> ListMessages = (List<Model.MessagesModel>)ViewData["Data"];
Int64 MessageId = 0;
Int64 SenderId = 0;
Int64 ReceiverId = 0;
string Message = null;
string Date = null;
string SendReceive = null;
int MessageType = 0;
}
<div class="main_Container">
<div>
<table>
<tr>
<td>Message ID</td><td>SenderID</td><td>recieverID</td><td>message</td><td>date</td>
</tr>
@foreach (var item in ListMessages)
{
MessageId = item.MessageId;
SenderId = item.SenderId;
ReceiverId = item.ReceiverId;
Message = item.Message;
Date = item.Date.ToShortDateString();
SendReceive = item.SendReceive;
MessageType = item.MessageType;
<tr>
<td>@MessageId</td>
<td>@SenderId</td>
<td>@ReceiverId</td>
<td>@Message</td>
<td>@Date</td>
</tr>
}
</table>
</div>
</div>
它返回“资源未找到”错误,这对我来说非常烦人,因为我尝试删除并重建 View ,但仍然无法解决它。我在这段代码中想做的另一件事是,使用 ajax 调用我发送将 contactNo 发送给 Controller , Controller 根据该 contactNo 号码检查相应的消息并将其传递给其查看消息。因此,当 ajax 调用响应成功完成后,它将重定向到消息 View 。
最佳答案
我认为您的 javascript 中的这一行会让您收到 404 - 未找到错误:
location.href = '@Url.Action("messages")';
我假设它尝试重定向到与您在问题中编写的代码完全相同的 Controller ,该 Controller 用 [HttpPost]
标记。
所以发生的情况是,您尝试 GET
标记为 [HttpPost]
的资源。
解决方案是删除 [HttpPost]
属性,或在该 Controller 中提供另一个接受 GET
请求的 messages
操作。
关于c# - 无法找到该资源。 MVC4,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22829225/