0

I have an MVC application with aspx file as the view. In the codebehind I have this function

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

In the aspx file I use ajax to call the method

$.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);
    }
});

The error I got is 404. I am not sure why. I have tried adding a new reference for system.web.extensions and download ajax extension. I have tried adding ignoreroute in the routeconfig. But nothing seems to be working. This is the controller.

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

Is the problem in the controller or maybe I am not supposed to use aspx for this?

Useme Alehosaini
  • 2,998
  • 6
  • 18
  • 26
Wolfeatspotatoes
  • 115
  • 1
  • 2
  • 10
  • I moved on to create a new project without MVC (strictly Web Form) and the code is working. If you have an unauthorized problem then pls refer to this [link](https://stackoverflow.com/questions/23033614/asp-net-calling-webmethod-with-jquery-ajax-401-unauthorized) . – Wolfeatspotatoes May 11 '20 at 04:35

1 Answers1

0

On my sandbox, everything is working as expected: 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>

Here is the 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!";
        }
    }
}

Hope this will help you in solving your issue.