Knockout.js行获胜't在MVC中验证

Knockout.js rows won't validate in MVC

本文关键字:MVC 验证 js 获胜 Knockout      更新时间:2023-09-26

我正在使用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>创建.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" />中的数据val似乎不工作?

我认为当你向SKUPrice数组添加一个新项时,Knockout会将一个新的<td>推送到你的DOM中,但这个新的DOM元素还没有应用MVC无结构验证。我不是MVC专家,但你可以试着将这行添加到addPrice:

self.addPrice = function () {
    self.SKUPrice.push({ count: "" });
    $.validator.unobtrusive.parse('#yourFormSelector')
};

当然,#yourFormSelector是一个jQuery选择器,用于访问<form>元素,我在HTML中看不到它。

顺便说一句,我发现你的<tbody>里面没有<tr>——这是故意的吗?这可能更正常:

<tbody data-bind="foreach: SKUPrice">
    <tr>
        <td>
            inputs...
        </td>
        <td>
            close link...
        </td>
    </tr>
</tbody>

在不使用MVC的JQuery.unobtrusive.validation.js的情况下回答了它,只使用了一个简单的查询进行验证。

$("input[name*=SRP]").each(function(){
    $(this).val($(this).val().trim());
    if($(this).val() == "") {
        err++;
        $("span[data-valmsg-for='" + $(this).attr("name") + "']").html("The field SRP is required.");
    } else if(isNaN($(this).val())) {
        err++;
        $("span[data-valmsg-for='" + $(this).attr("name") + "']").html("The field SRP must be a number.");
    } else {
        $("span[data-valmsg-for='" + $(this).attr("name") + "']").html("");
    }
});