[英]ASP.net web form access database using javascript instead of C#
I have an online shopping application where I have product categories. 我有一个在线购物应用程序,其中有产品类别。 I have the following method to retrieve the categories from the database and it is written in C#.
我有以下方法从数据库中检索类别,它是用C#编写的。
public IQueryable<Category> GetProductCategories()
{
var _db = new BundleShop.Models.ProductContext();
IQueryable<Category> query = _db.Categories;
return query;
}
Can anybody give me a hand writing the same code in javascript? 有人可以帮我用JavaScript编写相同的代码吗?
You cannot make a javascript call to the database. 您无法对数据库进行JavaScript调用。 The solution you are probably looking for is implementing a web service that exposes this functionality and call the webservice from the javascript (via ajax call).
您可能正在寻找的解决方案是实现公开此功能并从javascript(通过ajax调用)调用该Web服务的Web服务。
You can call with javascript one server side function that query the database. 您可以使用javascript调用查询数据库的一个服务器端函数。
server side (maybe in your home.aspx page) 服务器端(也许在您的home.aspx页中)
[WebMethod()]
[ScriptMethod(UseHttpGet = false, ResponseFormat = ResponseFormat.Json)]
public string[] GetProducts()
{
var _db = new BundleShop.Models.ProductContext();
IQueryable<Category> query = _db.Categories;
return query.Cast<MyEntityType>().ToArray();;
}
define your MyEntityType
Type 定义您的
MyEntityType
类型
public Class MyEntityType {
public int Order;
pubic string Description;
}
script side 脚本端
$.ajax({
type: "POST",
url: "/home.aspx/GetProducts",
success: onsuccess,
dataType: 'json',
error: onerror
});
manage results in success jquery function 管理成功jquery函数的结果
function onsuccess(data, status, xmlHttpRequest) {
//manage data variable here (cycle its elements, put them in page)
}
summarizing : 总结 :
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.