【问题标题】:ASP Web Pages Razor using AJAX to return array from DatabaseASP Web Pages Razor 使用 AJAX 从数据库返回数组
【发布时间】:2015-03-04 08:21:52
【问题描述】:

我正在使用 ASP 来完成我的课程作业,并且我正在使用 Razor 网页来执行应用程序。现在,我需要一些关于从 SQL 数据库中检索信息的帮助。

就目前而言,我进行了这样的 ajax 调用:

$.ajax({
    type: "POST",
    url: "/timetabler/Includes/ajaxModulesByUserId",
    data: { id: UserId  },
    success: function (data) {
        alert(data);
        if (data == "ERROR") {
            alert("We are unable to store the theme you have selected, therefore the change will not be permanent.");
        }
    }
});

这很简单地调用 ajaxModulesByUserId.cshtml 传递一个类似 1 的用户 ID。现在这非常棒地调用了文件。

现在我要在我的 CSHTML 中做的是获取请求的 ID,然后使用我的 C# 函数:

public IEnumerable<dynamic> getAllQuery(string query)
    {
        return _db.Query(query);
    }

执行我的查询。

现在我在我的 Razor 代码中这样称呼它:

string input = "";
    input = Request["id"];
    var arr = new List<string>();
    if (!string.IsNullOrEmpty(input))
    {
        // Add new sheet to database
        using (var repo = new initDatabase("SQLServerConnectionString"))
        {
            foreach (var row in repo.getAllQuery("SELECT * FROM Module WHERE userID = " + input))
            {
                arr.Add(""+row.moduleCode+","+row.moduleTitle+"");
            }
            @session.Serialize(arr);
        }
    }

所以我从数据库中返回行并将它们放入一个数组中,现在我的问题是,将这些值获取到 javascript。

就目前而言,我正在使用我从这里读到的技巧Stackoverflow,通过使用这样的函数:

public static string Serialize(object o)
    {            
        JavaScriptSerializer js = new JavaScriptSerializer();
        return js.Serialize(o);
    }

这实际上可以让我看到 Javascript 中的值,但是我遇到了这样的值:

我怎样才能收到一个干净的数组?甚至可能返回数据库中的所有行,因为我不得不以一种混乱的方式在 1 个数组字段中传递代码和标题,但用逗号分隔。

如果您能帮助我正确输出,将不胜感激。

谢谢

【问题讨论】:

    标签: javascript c# razor asp.net-webpages


    【解决方案1】:

    网页框架包含一个Json helper,它可以获取您的数据并将其作为 JSON 返回。

    if (!Request["id"].IsEmpty())
    {
        using (var repo = new initDatabase("SQLServerConnectionString"))
        {
            var data =  repo.getAllQuery("SELECT * FROM Module WHERE userID = @0", Request["id"])
            Json.Write(data, Response.Output);
        }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2020-05-05
      • 2020-09-28
      • 2020-02-03
      • 2018-06-29
      • 1970-01-01
      • 2014-09-01
      • 2021-12-15
      相关资源
      最近更新 更多