简体   繁体   中英

Call method in code-behind (secure page) from client (JavaScript)

Let me start of by saying I am very new to ASP.NET and C#. I have a simple web form containing data which I want to send to a code-behind page. The idea is to capture the data and send it as a JSON object to a code-behind method. Note that this is done via JavaScript/AJAX (see code below). The code-behind method will then do a trivial HTTP "PUT" request to update the data. The .apsx page is located in the Secure folder (uses a Secure Master). Don't know if that will affect the method calling?

Following is the code I have thus far.

JavaScript/AJAX:

var saveOptions =
{
  url: "Profile.aspx/UpdateVendor",
  type: "PUT",
  dataType: 'json',
  data: JSON.stringify({ vendor: ko.mapping.toJS(vendor) }),
  contentType: "application/json",

  success: function (response)
    {
    }
}

Code-behind:

namespace PartyAtVendors.Secure
{
  [WebService]
  public partial class Profile : System.Web.UI.Page
  {
    [WebMethod]
    public static bool UpdateVendor(PartyAtApi.Models.Vendors vendor)
    {
      return true;
    }
  }
}

Update:

Problem is as follows. The codebehind method isn't called. When I run and test the code and use Chrome's "inspect element" I receive the error:

PUT http://localhost:50671/Secure/Profile.aspx/UpdateVendor 404 (Not Found)

Such static methods are called Page Methods in asp.net.

You call them form javascript like this on the same page as follows:

string data = "{mydata:myvalue}";
PageMethods.UpdateVendor(data);

You need to have a ScriptManager on the page and it should have PageMethods enabled

<asp:ScriptManager runat="server" EnablePageMethods="true">
</asp:ScriptManager>

The page method must be defined on the page. It cannot be defined in a control, master page, or base page.

PageMethods only support HTTP POST(Even when you call them without the javascript proxy of PageMethods). You can read the details of this security limitation in this blog post by Scott Guthrie . Using the PUT verb is causing the 404 error.

ASP.NET AJAX 1.0 by default only allows the HTTP POST verb to be used when invoking web methods using JSON

您的webmethod和javascript方法应该在同一页上。

Hi managed to sort out what was wrong.

I simply changed the HTTP method to "POST" as follows:

var saveOptions =
{
  url: "Profile.aspx/UpdateVendor",
  type: "POST",
  dataType: 'json',
  data: JSON.stringify({ vendor: ko.mapping.toJS(vendor) }),
  contentType: "application/json",

  success: function (response)
  {
  }
}

$.ajax(saveOptions);

This seemed to fix the problem and now I am able to send the JSON data to the codebehind method using AJAX.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM