【发布时间】:2015-05-19 11:08:45
【问题描述】:
我正在使用 MVC、C#、Razor 和 Knockout.js
模型 > SKUPrice.cs
[Required]
[Display(Name = "SRP")]
public Decimal SRP { get; set; }
控制器 > SKUPriceController.cs
public ActionResult Create(int id = 1)
{
return View();
}
[HttpPost]
public ActionResult Create(List<SKUPrice> skuprices)
{
if (ModelState.IsValid) {
foreach (SKUPrice skuprice in skuprices)
{
db.SKUPrices.AddObject(skuprice);
db.SaveChanges();
}
}
}
return View();
视图 > SKUPrice > Create.cshtml
<table>
<thead>
<tr>
<th>
@Html.LabelFor(model => model[0].SRP)
</th>
<th>
</th>
<tr>
<tr>
<td>
<input class="form-control" data-val="true" data-val-number="The field SRP must be a number."
data-val-required="The SRP field is required." name="[0].SRP" type="number" value="0" step="0.25">
<span class="help-block"><span class="field-validation-valid" data-valmsg-for="[0].SRP"
data-valmsg-replace="true"></span></span>
</td>
<td>
<input type="button" onclick="" value="Add" class="btn btn-primary" data-bind="click: addPrice">
</td>
</tr>
</thead>
<tbody data-bind="foreach: SKUPrice">
<td>
<input class="form-control" data-val="true" data-val-number="The field SRP must be a number."
data-val-required="The SRP field is required." type="number" value="0" step="0.01" data-bind="attr: { name: '[' + ($index() + 1) + '].SRP'}">
<span class="help-block"><span class="field-validation-valid" data-valmsg-replace="true"
data-bind="attr: { 'data-valmsg-for': '[' + ($index() + 1) + '].SRP'}"></span>
</span>
</td>
<td>
<i class="fa fa-close" data-bind="click: $parent.removePrice" style="cursor: pointer; color: Red;"></i>
</td>
</tbody>
</table>
<input type="submit" value="Save" name="Save" class="btn btn-primary" />
脚本 > main.js
function ViewModel() {
var self = this;
self.SKUPrice = ko.observableArray([]);
self.addPrice = function () {
self.SKUPrice.push({ count: "" });
};
self.removePrice = function () {
self.SKUPrice.remove(this);
};
}
ko.applyBindings(new ViewModel());
当我在第一行输入非数字并单击保存时,它已验证,但当我添加第二行并输入非数字值时,它不会验证除第一行之外的其他行。这有什么问题?
<input type="text" data-val="true" /> 中的 data-val 似乎不起作用?
【问题讨论】:
-
我们能看到更多的 rour main.js 吗?您可能在某个地方有一些应用验证插件的代码 - 我认为这是关键 - 我将在下面草拟一个答案来解释。
标签: javascript c# asp.net-mvc asp.net-mvc-4 knockout.js