gpt4 book ai didi

c# - 如何允许访问 MVC 中的方法?

转载 作者:太空宇宙 更新时间:2023-11-03 18:38:22 24 4
gpt4 key购买 nike

我正在尝试对我的 MVC 项目中的模型进行 AJAX 调用。我不断收到以下错误:

POST foobar/GetDate 405 (Method Not Allowed)

(其中“foobar”是我的 MVC 项目的 localhost:port 格式。)

我还没有在项目中尝试过路由,因为我不确定脚本的路由应该是什么样子。我现在知道如何正确路由 View 。以下是一些代码片段:

在我的 MVC 项目中,我有一个具有以下方法的模型:

[WebMethod]
public static string GetDate()
{
return DateTime.Now.ToString();
}

在我的 Index.aspx 文件中,我有这段代码:

<button class="getDate">Get Date!</button>
<div class="dateContainer">Empty</div>

在我的 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);
}
},
});

我的最终目标是将 XML 数据发送到我在 C# 模型中的方法,然后解析并保存 XML 文档。

现在,我将尝试将 jQuery 中的 AJAX 请求链接到我拥有的 C# 方法。我肯定它与路由和语法有关。

提前致谢!

最佳答案

为什么在 MVC 项目中有一个 [WebMethod] 方法?

在 MVC 中,您可以在 controller 中使用 action 方法。您也可以从 ajax 调用它

public class WebController : Controller
{
public ActionResult GetDate()
{
return Content(DateTime.Now.ToString());
}
}

你可以像这样从你的 javascript 中调用它(使用 jQuery)

$.get("@url.Action("GetDate","Web")",function(result){
alert("The result from ajax call is "+result);
});

如果您正在对该方法执行 POST 调用,请确保使用 POST 属性修饰您的操作方法。

    [HttpPost]
public ActionResult SaveUser(string userName)
{
//do something and return something
}

您甚至可以将 JSON 从您的操作方法返回到您的 ajax 调用的回调函数。 Controller(我们 WebController 的基类)类中有一个 JSON 方法来执行此操作。

    public ActionResult GetMagician(string userName)
{
return Json(new { Name="Jon", Job="Stackoverflow Answering" },
JsonRequestBehavior.AllowGet);
}

关于c# - 如何允许访问 MVC 中的方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11909785/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com