我正在使用敲除JS,并努力从我的模型中获取一个下拉列表。
我猜我需要先将模型数据转换为JSON,但终生无法弄清。
我有一个基础课:
public class QuoteViewModel
{
public QuoteViewModel()
{
QuoteLines = new List<QuoteLine>();
}
public int QuoteHeaderId { get; set; }
public string QuoteNumber { get; set; }
public string Status { get; set; }
public DateTime DateCreated { get; set; }
[DisplayName("Customer")]
public SalesCustomer SelectedCustomer { get; set; }
public List<string> Customers { get; set; }
public List<QuoteLine> QuoteLines { get; set; }
}
我在控制器中有一个ActionMethod:
[HttpGet]
public ActionResult CreateQuote()
{
QuoteViewModel quote = new QuoteViewModel();
quote.QuoteNumber = "";
quote.Status = "P";
quote.Customers = _dbContext.SalesCustomers.Select(x => x.CustomerName).ToList();
quote.QuoteLines = new List<QuoteLine>();
return View(quote);
}
和View():
剃刀:
<select class="form-control" id="SelectedCustomer" data-bind="options: availableCustomers, optionsText: 'CustomerName', value: SelectedCustomer, optionsCaption: 'Choose...'"></select>
ViewModel:
function QuoteViewModel() {
var self = this;
self.Id = ko.observable('@Model.QuoteHeaderId');
self.QuoteNumber = ko.observable();
self.Status = ko.observable('@Model.Status');
self.DateCreated = ko.observable();
self.availableCustomers = JSON.parse('@Html.Raw(Model.Customers)');
@*$.ajax({
type: "GET",
url: '@Url.Action("GetCustomers", "Test")',
success: function (data) {
$.each(data, function (index, value) {
self.availableCustomers.push(new Customer(value));
});
},
error: function (err) {
console.log(err.responseText);
}
});*@
self.SelectedCustomer = ko.observable();
self.QuoteLines = ko.observableArray([]);
self.AddQuoteLine = function (sku, description, bomDetails) {
self.QuoteLines.push(new QuoteLineViewModel(sku, description, bomDetails));
}
self.SaveToDatabase = function () {
var dataToSend = ko.mapping.toJSON(self);
$.ajax({
type: "POST",
url: '@Url.Action("CreateQuote", "Test")',
contentType: 'application/json',
data: dataToSend,
success: function (data) {
},
error: function (err) {
console.log(err.responseText);
}
});
}
注释掉的代码使用ajax吸引客户并将其推送到数组上,并且可以正常工作,但是没有办法直接从模型数据中进行操作吗?
编辑1:
我不需要访问整个SalesCustomer对象,只需访问字符串名称:
如果我这样更改代码:
控制器:
quote.Customers = _dbContext.SalesCustomers.Select(x => x.CustomerName.Trim()).ToList();
模型类属性:
public List<string> Customers { get; set; }
剃刀:
<select class="form-control" id="SelectedCustomer" data-bind="options: availableCustomers, value: SelectedCustomer, optionsCaption: 'Choose...'"></select>
Javascript:
self.availableCustomers = ko.observableArray([]);
var customers = '@Html.Raw(JsonConvert.SerializeObject(Model.Customers))';
self.availableCustomers = JSON.parse(customers);
self.SelectedCustomer = ko.observable();
现在,在下拉列表中填充客户名称的字符串值。但是,所选客户是否不会在POST上传递回控制器?
编辑2:
好吧,我不确定为什么它现在可以正常工作,但是确实可以。
代码与编辑1中的代码相同。
我唯一能想到的是我错误地将SelectedCustomer属性类型设置为SalesCustomer,这显然不起作用:
public SalesCustomer SelectedCustomer { get; set; }
应该在什么时候出现:
public string SelectedCustomer { get; set; }
谢谢user3297291为我指出正确方向的帮助。