Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can't access the code behind using ajax post in asp.net

Tags:

ajax

asp.net

This is my code behind:

enter image description here

This is my KO Script:

enter image description here

this is the result when I click my submit button enter image description here

I there anything wrong with my code?

like image 674
comfreakph Avatar asked Nov 26 '25 12:11

comfreakph


2 Answers

I have downloaded your solution and got it working

In App_Start\RouteConfig.cs you have the following line which needs to be removed:

settings.AutoRedirectMode = RedirectMode.Permanent;

Also your web method needs to be static

like image 77
Martin Davies Avatar answered Nov 29 '25 02:11

Martin Davies


In App_Start\RouteConfig.cs Change

settings.AutoRedirectMode = RedirectMode.Permanent; 

to

settings.AutoRedirectMode = RedirectMode.Off;

If the web method is not static in code behind, it will not work.
If you really want to continue using code behind, you can do so by creating a static method.
Example:

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;
        }
    }
}
}

An easier alternative is to create a webservice (.ASMX) using instance methods.

like image 24
Kevin Avatar answered Nov 29 '25 03:11

Kevin



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!