bdr*_*ing 1 c# ajax asp.net-mvc
我正在尝试对我在MVC项目中的模型进行AJAX调用.我一直收到以下错误:
POST foobar/GetDate 405(方法不允许)
('foobar'是我的localhost:MVC项目的端口格式.)
我还没有在项目中使用路由,因为我不确定脚本的路径应该是什么样子.我知道如何在这一点上正确地路由视图.以下是一些代码段:
在我的MVC项目中,我有一个使用以下方法的模型:
[WebMethod]
public static string GetDate()
{
return DateTime.Now.ToString();
}
Run Code Online (Sandbox Code Playgroud)
在我的Index.aspx文件中,我有这个代码:
<button class="getDate">Get Date!</button>
<div class="dateContainer">Empty</div>
Run Code Online (Sandbox Code Playgroud)
在我的script.js文件中,我有这个代码:
$.ajax({
type: "POST",
url: "GetDate",
data: "{}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (msg) {
// Replace text in dateContainer with string from GetDate method
$(".dateContainer").text(msg.d);
},
complete: function (jqHXR, textStatus) {
// Replace text in dateContainer with textStatus
if (textStatus != 'success') {
$(".dateContainer").text(textStatus);
}
},
});
Run Code Online (Sandbox Code Playgroud)
我的最终目标是在C#模型中将XML数据发送到我的方法,然后解析并保存XML文档.
现在,我将尝试将jQuery中的AJAX请求链接到我拥有的C#方法.我很肯定它与路由和语法有关.
提前致谢!
为什么[WebMethod]MVC项目中有方法?
在MVC中,您可以action在自己controller的方法中使用方法.你也可以从ajax调用它
public class WebController : Controller
{
public ActionResult GetDate()
{
return Content(DateTime.Now.ToString());
}
}
Run Code Online (Sandbox Code Playgroud)
你可以用这样的javascript调用它(使用jQuery)
$.get("@url.Action("GetDate","Web")",function(result){
alert("The result from ajax call is "+result);
});
Run Code Online (Sandbox Code Playgroud)
如果您正在POST调用该方法,请确保使用POST属性修饰您的操作方法.
[HttpPost]
public ActionResult SaveUser(string userName)
{
//do something and return something
}
Run Code Online (Sandbox Code Playgroud)
你甚至可以从你的action方法返回JSON到你的ajax调用的回调函数.JSON在Controller(我们的WebController的基类)类中有一个方法来执行此操作.
public ActionResult GetMagician(string userName)
{
return Json(new { Name="Jon", Job="Stackoverflow Answering" },
JsonRequestBehavior.AllowGet);
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
232 次 |
| 最近记录: |