使用Ajax ASP.NET从数据库获取信息 [英] Get information from database with ajax ASP.NET
问题描述
每当select
字段更改时,我都试图从数据库的表中获取一些信息.
I'm trying to get some information from a table in my database whenever a select
-field changes.
我能够执行响应,并且Ajax jQuery函数返回成功(函数)
问题是我不知道如何使用ASP.net MVC从数据库返回数据.
我从Ajax调用成功获得的响应是以下文本:
I'm able to do the response and the Ajax jQuery function return success(function)
The problem is i don't know how to return the data from my database using ASP.net MVC.
The response i'm getting from my Ajax call on success is this text:
ProduktWebKort.Models.WarehouseCustomer[]
这是我的控制器的一部分,它具有通过Ajax调用的功能
This is the part of my controller with the function called via Ajax
[HttpPost]
public string OnChange(int id)
{
return db.Customers.Where(C => C.CustomerID == id).ToString();
}
我的Ajax呼叫看起来像这样:
My Ajax call looks like this:
<script type="text/javascript">
$(function () {
// Document.ready -> link up remove event handler
$("#CustomerID").change(function () {
alert("Hej");
var option = $('option:selected', this).val();
$.ajax({
type: "POST",
url: '@Url.Action("Index/1", "Session")',
contentType: "application/json; charset=utf-8",
data: { id: 1 },
dataType: "html",
success: function (success) {
alert('Success');
console.log(success);
for (var i = 0; i < success.length; i++) {
$(".form-horizontal").append("<li>" + success[i] + " </li>");
console.log(success);
}
},
error: function (e, text, string) {
alert(e.message + text + string);
console.log(e);
}
});
});
});
</script>
我想从我的选择字段中返回ID为CustomerID
的WarehouseCustomer
中的每个条目.
I want to return every entry from WarehouseCustomer
with the CustomerID
of id from my select field.
推荐答案
服务器端和客户端的问题.
如果要在服务器端获得客户的List
,则应这样编写Controller
:
Your problem on both server and client side.
If you want to get List
of customers on server side you should write your Controller
like this:
[HttpPost]
public JsonResult OnChange(int id)
{
return Json(db.Customers.Where(C => C.CustomerID == id).ToList());
}
如果要使用IEnumerable
结果,应在客户端更改如下的ajax代码:
On client side you should change your ajax code like this if you want to work with IEnumerable
result:
$.ajax({
type: "POST",
url: '@Url.Action("OnChange", "Session")',
data: { id: 1 },
dataType: "json",
success: function (success) {
alert('Success');
console.log(success);
$.each(success, function (i, item) {
$(".form-horizontal").append("<li>" + item.CustomerID + "</li>");
});
},
error: function (e, text, string) {
alert(e.message + text + string);
console.log(e);
}
});
我希望您的OnChange
方法在Session
Controller
中.据了解,您可以访问列表元素的其他属性,例如(item.CustomerID
).
I hope your OnChange
method is in Session
Controller
. You can access other properties of your list elements like this (item.CustomerID
), as you understand.
这篇关于使用Ajax ASP.NET从数据库获取信息的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!