【问题标题】:How to call c# functions using ajax in razor web pages如何在剃须刀网页中使用ajax调用c#函数
【发布时间】:2018-06-15 18:10:30
【问题描述】:

我正在尝试为我的电子商务网站添加一个上传表单,我需要为类别和子类别选择框。当我选择一个类别时,我想要一个 ajax 函数使用我的 sql server 子类别表中的子类别列表自动填充其他选择框选项。我无法让 ajax 函数的 url 部分正常工作,也无法找到与我的 c# 类和 cshtml 页面一起使用的正确 url。谢谢你。 [这是我的测试 cshtml 页面列表中想要用于测试的测试 ajax 函数的图片] (https://i.stack.imgur.com/988Rg.png)

@{ 
    Layout = "~/_SiteLayout3.cshtml";
}
<script>
    $(document).ready(function () {
        $.ajax({
            type: "POST",
            url: '<%= ResolveUrl("~/Shared/MySite1.cs/GetData2") %>',
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            success: function (response) {
                $("#Content").text(response.d);
            },
            failure: function (response) {
                alert(response.d);
            }
        });
    });
</script>

<form id="frm" method="post">
    <div id="Content">

    </div>

</form>

My C# Code

using System;
using System.Linq;
using System.Collections.Generic;
using System.Text;
using System.Web.Services;


public static class MySite1
{
    [WebMethod]
    public static string GetData2()
    {
        return "This string is from Code behind";
    }

}

【问题讨论】:

  • 嗨,Ahmed,请尝试将您的代码放入问题的正文中。
  • 好的,但这只是一个测试
  • 考虑这个链接:c-sharpcorner.com/blogs/…
  • @Frankenstine Joe,我没有使用 mvc,我使用的是网页,我认为我无法向网页添加控制器和视图

标签: c# jquery asp.net ajax razor


【解决方案1】:

对我来说已经有一段时间了,所以如果没有记错的话,在ASP.Net Web Pages 中,它更像是“裸机”。您必须自己处理 HTTP 请求。

这个琐碎的示例使用.cshtml,但由于这仍然是“ASP.Net”,您也可以使用通用处理程序(.ashx)(因为没有“内容”需要,只是您的 XHR 请求处理的一些结果)。

<p>Ajax result appears below:</p>
<p id="result"></p>

<script>
    $(function () {
        $("#ajaxTest").on("click", function () {

            var request = $.ajax({
                type: "POST",
                url: "/ajaxhandler",
                data: { "foo": "1234bar" }
            });

            request.done(function (d) {
                console.log(d);
                $("#result").text(d);
            });

            request.fail(function (xhr, err) {
                console.log("It died...%o", err);
            });
        });
    })
</script>

在上面/ajaxhandler 是一个.cshmtl 文件(如上你可以使用.ashx 代替):

ajaxhandler.cshtml:

@{

    if (IsPost)
    {
        var payload = "";
        using (var reader = new StreamReader(Request.InputStream))
        {
            payload = reader.ReadToEnd();
        }

        Response.AddHeader("Content-Type", "text/text");
        Response.Write(payload);

    }

}

您可以通过检查 HTTP 请求(例如 url、片段、查询字符串等)来扩展它并进行相应的处理。

Hth.

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-09-13
    • 2021-10-07
    • 2021-10-20
    • 2020-04-15
    • 2019-09-02
    • 1970-01-01
    • 2021-12-22
    相关资源
    最近更新 更多