我正在使用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中的值,但是当我最终得到这样的值时,我会陷入困境:
我怎样才能收到干净的阵列?甚至可能甚至返回数据库中的所有行,因为我不得不在一个数组字段中传递代码和标题的混乱方式,但用逗号分隔。
如果你能帮我正确输出,我真的很感激。
由于
答案 0 :(得分:0)
网页框架包含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);
}
}