Ajax 在响应中返回 MasterPage 文件,而不是从当前页面的方法返回

问题描述 投票:0回答:1

Ajax 返回母版页 html,而不是从我的方法返回。

这是我的客户代码:

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Page1.aspx.cs" Inherits="Page1"
    MasterPageFile="~/MasterPage.master" EnableEventValidation="false" %>

function saveForm() {
    
    let formData = new FormData();
    formData.append("name", "john");

    $.ajax({
        type: "POST",
        url: 'Page1.aspx?method=SaveForm',
        data: formData,
        contentType: false,
        processData: false,
        cache: false,
        success: onSuccessSaveForm,
        failure: function (response) {
            alert(response.d);
        },
        error: function (response) {
            alert(response.d);
        }
    });
}

这是我的服务器代码:

public partial class Page1 : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        if (Request.QueryString["method"] != string.Empty && Request.QueryString["method"] != null)
        {
            Type thisType = this.GetType();
            MethodInfo theMethod = thisType.GetMethod(Request.QueryString["method"]);
            theMethod.Invoke(this, null);
        }
    }
}

public string SaveForm()
{
    Result result = new Result();
    ...code
    return JsonConvert.SerializeObject(result); -->(*expect to return this)
}

期望:

停在

theMethod.Invoke(this, null)
并返回到我的ajax调用

结果:

它继续到 MasterPage.master.cs 的

page_load
方法,并返回整个 html 作为结果

如何将结果从

theMethod.Invoke(this, null)
传递到前端。如果可能的话,也不必去 MasterPage.master.cs 也不涉及刷新页面,例如使用
[System.Web.Services.WebMethod]

c# jquery asp.net webforms
1个回答
0
投票

奥莱特。所以基本上,我所要做的就是将结果写入 Response,然后结束它。所以 page_load 方法将是:

public partial class Page1 : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        if (Request.QueryString["method"] != string.Empty && Request.QueryString["method"] != null)
        {
            Type thisType = this.GetType();
            MethodInfo theMethod = thisType.GetMethod(Request.QueryString["method"]);
            string result = theMethod.Invoke(this, null).ToString();

            Response.Write(result);
            Response.End();
        }
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.