【发布时间】:2014-12-01 08:43:20
【问题描述】:
我正在使用 ajax 来调用控制器中的操作。代码是这样的
$('#kitchen').change(function () {
var selectedKitchen = $('#kitchen').val();
if (selectedKitchen != '') {
console.log("selected item:" + $('#kitchen').val());
$.ajax({
type: "GET",
url: "/Home/GiveInsitutionsWithoutResponsibility",
data: "id=" + selectedKitchen,
dataType:'json',
success: function (result) {
result = JSON.parse(result);
console.log(result.length);
},
error: function (error) {
console.log("There was an error posting the data to the server: ");
console.log(error.responseText);
}
});
}
});
现在我想要的是使用来自服务器的结果来填充客户端的下拉列表。我该怎么做?有没有办法或者我的方法是错误的?
我的结果对象是这样的
{
Id: "04409314-ea61-4367-8eee-2b5faf87e592"
Name: "Test Institution Two"
NextPatientId: 1
OwnerId: "1"
PartitionKey: "1"
RowKey: "04409314-ea61-4367-8eee-2b5faf87e592"
Timestamp: "/Date(1417180677580)/"
}
控制器功能是这样的
public ActionResult GiveInsitutionsWithoutResponsibility()
{
var kitchenId = Request["id"].ToString();
Kitchen k = Kitchen.Get(kitchenId);
IEnumerable <Institution> ins = k.GetInstitutions();
IEnumerable<Institution> allIns = Institution.GetAll();
List<Institution> result = new List<Institution>();
bool contain = true;
int index = 0;
if (ins.Count() > 0)
{
for (int i = 0; i < allIns.Count(); i++, contain = true)
{
for (int j = 0; j < ins.Count(); j++)
{
if (allIns.ElementAt(i).Id == ins.ElementAt(j).Id)
{
contain = true;
break;
}
else
{
index = j;
contain = false;
}
}
if (!contain)
{
result.Add(allIns.ElementAt(index));
}
}
}
else
{
for (int i = 0; i < allIns.Count(); i++)
{
result.Add(allIns.ElementAt(index));
}
}
string response = new System.Web.Script.Serialization.JavaScriptSerializer().Serialize(result);
return Json(response, JsonRequestBehavior.AllowGet);
}
【问题讨论】:
-
您错过了
dataType:'json',,您可以参考$('#kitchen')和$(this),这将是一个好方法。 -
谢谢。我已经编辑了我的代码,但是关于如何使用结果对象有什么建议吗?
-
你的
result object到底是什么?你能把它贴出来看看它有什么结构吗? -
刚刚编辑了带有回复的问题。
-
似乎是一个无效对象。检查jsonlint.com,尤其是这里
ETag: "W/"datetime'2014-11-28T13%3A17%3A57.58Z'"",对象中的第一个。
标签: c# jquery ajax asp.net-mvc razor