【问题标题】:Can't access the code behind using ajax post in asp.net无法在asp.net中使用ajax post访问背后的代码
【发布时间】:2014-01-25 11:10:47
【问题描述】:

这是我的代码:

这是我的 KO 脚本:

这是我单击提交按钮时的结果

我的代码有什么问题吗?

【问题讨论】:

标签: asp.net ajax


【解决方案1】:

我已经下载了您的解决方案并开始使用

App_Start\RouteConfig.cs 中有以下需要删除的行:

settings.AutoRedirectMode = RedirectMode.Permanent;

你的网络方法也需要是static

【讨论】:

  • 仍然收到身份验证失败消息
【解决方案2】:

App_Start\RouteConfig.cs 改变

settings.AutoRedirectMode = RedirectMode.Permanent; 

settings.AutoRedirectMode = RedirectMode.Off;

如果 web 方法在后面的代码中不是静态的,它将无法工作。
如果您真的想继续使用后面的代码,可以通过创建静态方法来实现。
示例:

public class Customer
{
    public string CustomerId { get; set; }
    public string ContactName { get; set; }
    public string City { get; set; }
    public string Country { get; set; }
    public string PostalCode { get; set; }
    public string Phone { get; set; }
    public string Fax { get; set; }
}

[WebMethod]
public static List<Customer> GetCustomers()
{
    string constr = ConfigurationManager.ConnectionStrings["constr"].ConnectionString;
    using (SqlConnection con = new SqlConnection(constr))
    {
        using (SqlCommand cmd = new SqlCommand("SELECT TOP 10 * FROM Customers"))
        {
            cmd.Connection = con;
            List<Customer> customers = new List<Customer>();
            con.Open();
            using (SqlDataReader sdr = cmd.ExecuteReader())
            {
                while (sdr.Read())
                {
                    customers.Add(new Customer
                    {
                        CustomerId = sdr["CustomerId"].ToString(),
                        ContactName = sdr["ContactName"].ToString(),
                        City = sdr["City"].ToString(),
                        Country = sdr["Country"].ToString(),
                        PostalCode = sdr["PostalCode"].ToString(),
                        Phone = sdr["Phone"].ToString(),
                        Fax = sdr["Fax"].ToString(),
                    });
                }
            }
            con.Close();
            return customers;
        }
    }
}
}

更简单的替代方法是使用实​​例方法创建 Web 服务 (.ASMX)。

【讨论】:

    猜你喜欢
    • 2017-12-17
    • 2012-06-17
    • 2011-09-05
    • 2021-04-25
    • 1970-01-01
    • 1970-01-01
    • 2020-07-30
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多