【问题标题】:Correct way of adding Page Method to ASP MVC project?将页面方法添加到 ASP MVC 项目的正确方法?
【发布时间】:2012-04-11 23:12:16
【问题描述】:

我刚刚开始使用 ASP.NET 和 MVC 模型。我已经围绕基本概念进行了研究,并且有一些模型、控制器和视图工作正常。我知道如何将 Web 方法和页面方法添加到 Web 服务,但无法为 MVC 项目解决。

我(认为)我需要在我的项目中添加一个页面方法作为响应 AJAX 请求的正确方法。这是我的控制器的样子:

namespace MyProject
{
    public class OrderController : Controller
    {
        public ActionResult Place (ProductSku sku)
        {           
            var order = Order.NewOrder(sku);
            var db = new SystemDiscsLib.Database();
            db.SaveOrder(order);

            return View(order);
        }

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

发布到/Order/Place 工作正常,创建的视图显示Views/Order/Place.aspx 的内容,每个人都很高兴。但是,对/Order/GetDate 发出的任何请求都会失败并出现The resource cannot be found 错误。我(认为)通过将其添加到我的Web.config,在system.web 下,我已经正确启用了页面方法:

    <httpModules>
        <add name="ScriptModule" type="System.Web.Handlers.ScriptModule, System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"/>
    </httpModules>

我没有名为GetDate 的视图,因为我不想要视图,我只会返回 JSON 数据。我打算使用JQuery,所以我没有做EnablePageMethodsScripManager的东西,per this article

【问题讨论】:

    标签: asp.net asp.net-mvc pagemethods webmethod


    【解决方案1】:

    PageMethods 用于 WebForms,而不是 MVC。更改您的方法,使其看起来更像这样:

    public JsonResult GetDate()
    {
      return Json(DateTime.Now.ToString());
    }
    

    请注意,该方法不再是静态的,您不应使用[WebMethod] 属性。

    【讨论】:

    • +1 这是对的,我以为OP想在他们看来使用这种方法,而错过了使用jquery的请求。
    • 这太简单了,如果我还没有读过 PageMethods 让我在错误的树上吠叫的话,那就很明显了。谢谢。
    • 我相信它也在 System.Web.Mvc 中?
    猜你喜欢
    • 1970-01-01
    • 2021-10-16
    • 2021-04-28
    • 1970-01-01
    • 2014-11-01
    • 2019-06-15
    • 1970-01-01
    • 1970-01-01
    • 2014-12-08
    相关资源
    最近更新 更多