我正在开发一个带有 knockout.js 的网络表单。有一次,我根据列表中的选定值得到一个值select
。我在 viewModel 中有以下代码:
self.discoveryForms = ko.observableArray([]);
self.selectedTemplate = ko.observable();
self.selectedDiscoveryForm = ko.observable();
//behaviors
self.selectedTemplate.subscribe(function (newValue) {
console.log(newValue.DiscoveryFormID());
self.GetDiscoveryForms(newValue.DiscoveryFormID());
});
self.GetDiscoveryForms = function (discoveryFormID) {
console.log(discoveryFormID);
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
data: "{ID: '" + discoveryFormID + "'}",
url: ("Default.aspx/GetDiscoveryForms"),
dataType: "json",
success: function (response) { self.FindDiscoveryForms(response), console.log(response)}
});
}
self.FindDiscoveryForms = function (response) {
ko.mapping.fromJS(response.d, null, viewModel.discoveryForms);
ko.applyBindings(viewModel);
}
从实体获取数据的 c# 是这样的:
[WebMethod]
public static List<DiscoveryForm> GetDiscoveryForms(){
List<DiscoveryForm> discoveryForms = new List<DiscoveryForm>();
using (IntranetContainer db = new IntranetContainer())
{
discoveryForms = db.DiscoveryForms.Select(x => new DiscoveryForm()
{
ID = x.ID,
Name = x.Name,
Welcome = x.Welcome,
WelcomeNote = x.WelcomeNote,
WelcomeBack = x.WelcomeBack,
WelcomeBackNote = x.WelcomeBackNote
}).ToList();
}
return discoveryForms;
}
public class DiscoveryForm
{
public long ID { get; set; }
public string Name { get; set; }
public string Welcome { get; set; }
public string WelcomeNote { get; set; }
public string WelcomeBack { get; set; }
public string WelcomeBackNote { get; set; }
}
问题是,虽然我希望 ajax 请求只返回ID
由 选择的发现表单selectedTemplate
,但它目前将所有值返回到数组中。我认为那data: "{ID: '" + discoveryFormID + "'}",
会做到这一点。有人可以向我解释为什么会这样以及如何解决吗?我应该在 c# 方面做些什么吗?我是 javascript、ajax 和 knockout.js 的新手。
为了纠正这个问题,查询必须如下所示:
data: "{'id':"+discoveryFormID + "}",
并且根据下面的答案更改了c#方法。