【问题标题】:AJAX calling for web form in MVCAJAX 在 MVC 中调用 Web 表单
【发布时间】:2020-08-26 02:37:45
【问题描述】:

我有一个MVC 应用程序,其中aspx 文件作为视图。在代码隐藏中我有这个功能

[WebMethod]
public static string GetProduct1()
{
    return "Hi!";
}

aspx文件中我使用ajax调用方法

$.ajax({
    type: "POST",
    url: "selection.aspx/GetProduct1",
    data: "{}",
    contentType: "application/json; charset=utf-8",
    dataType: "json",
    success: function (msg) {
        // Do something interesting with msg.d here.
        console.log(msg);
    },
    error: function (response) {
        console.log(response);
    }
});

我得到的错误是404。我不确定为什么。我尝试为system.web.extensions 添加新参考并下载ajax 扩展。我尝试在 routeconfig 中添加 ignoreroute。但似乎没有任何效果。这是控制器。

public ActionResult selection()
{
     ViewBag.Title = "Home Page";
            
     return View();
}

是控制器的问题还是我不​​应该为此使用aspx?

【问题讨论】:

  • 我继续创建一个没有 MVC(严格来说是 Web 表单)的新项目,并且代码可以正常工作。如果您有未经授权的问题,请参考此link

标签: c# asp.net ajax asp.net-mvc webforms


【解决方案1】:

在我的沙盒上,一切都按预期工作:WebForm1.aspx

 <%@ Page Language="C#" AutoEventWireup="true" CodeBehind="WebForm1.aspx.cs" Inherits="WebApplication2.WebForm1" %>

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
        <div>
        </div>
    </form>
    <script>
        $(function () {
            $.ajax({
                type: "POST",
                url: "WebForm1.aspx/GetProduct1",
                data: "{}",
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                success: function (msg) {
                    // Do something interesting with msg.d here.
                    console.log(msg);
                },
                error: function (response) {
                    console.log(response);
                }
            });
        });
    </script>
</body>
</html>

这里是 WebForm1.aspx.cs

using System;
using System.Web.Services;

namespace WebApplication2
{
    public partial class WebForm1 : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
        }

        [WebMethod]
        public static string GetProduct1()
        {
            return "Hi!";
        }
    }
}

希望这将帮助您解决问题。

【讨论】:

  • 我想知道这是否是 MVC 的问题。当我创建和测试其他框架(Web 表单)时,它按预期工作。
猜你喜欢
  • 2016-02-08
  • 1970-01-01
  • 1970-01-01
  • 2015-05-03
  • 2013-08-29
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-12-19
相关资源
最近更新 更多