List从控制器发送到索引时总是返回空值



我已经尝试了20种不同的方法,并在谷歌上搜索了这个问题,但我仍然卡住了。我的列表总是返回一个空值。当我调试时,我可以看到值来自数据库,一切似乎都很好。

但是,当我使用console.log在视图中调试时,它总是空的。

这是我的模型:

public class GarageModel
{
public int GarageId { get; set; }
public int Values { get; set; }
}

c#方法:

public List <GarageModel> getRequestType(int garageId)
{
List<GarageModel> newList = new List<GarageModel>();
string sql = "SELECT GarageID, RequestProperty FROM GarageCrossRequestType 
WHERE GarageID = " + garageId;
var cmd = new SqlCommand(sql, Connection);
var dt = new DataTable();
dt.Load(cmd.ExecuteReader());
foreach (DataRow i in dt.Rows)
{
var model = new GarageModel();
model.GarageId = Convert.ToInt32(i["GarageID"].ToString());
model.Values = Convert.ToInt32(i["RequestProperty"].ToString());
newList.Add(model);
}
return newList;
// returns the values from database 
}

Javascript/jQuery:

function editGarage(e) {
e.preventDefault();
var dataItem = this.dataItem($(e.currentTarget).closest("tr"));
var garageId = dataItem.GarageId;
countryId = dataItem.CountryId;
name = dataItem.Name;
customerNumberOfEditingGarage = dataItem.CustomerNumber;
var Values = dataItem.Values;
$.ajax({
type: 'POST',
url: '@Url.Action("getRequestType", "Garage")?garageId=' + garageId,
dataType: 'JSON',
data: {
Values: Values, garageId: garageId
},
});
console.log(garageId, Values);
// always return correct garageId but null in Values
// or whatever value is set to Values in the model

我错过了什么?

就像我说过的,我尝试过不同的方法,我在get/post之间改变了类型,我把方法改成了bool, int等等,但我迷路了,老实说,我也不太擅长JavaScript/jQuery,所以我很感激你的帮助。

要指定,我想要的结果只是看到我从方法/数据库中获得的值,当我在浏览器中使用console.log进行调试时显示。

你的getRequestType方法只需要一个参数,values不是一个参数,所以只发送garageId,当你的ajax成功时,你需要填充values

$.ajax({
type: 'POST',
url: '@Url.Action("getRequestType", "Garage")',
dataType: 'JSON',
data: {
garageId: garageId
},
success: function(data){
values = data;
console.log(garageId, data);
}
});

控制器方法需要返回JsonResult而不是list

public JsonResult /*List<GarageModel>*/ getRequestType ...

return Json(newList, JsonRequestBehavior.AllowGet);

最新更新