【问题标题】:Conditionally unobtrusive validation mode有条件的不显眼的验证模式
【发布时间】:2017-09-12 10:02:11
【问题描述】:

我正在使用 Razor、C# 和 .NET Framework 4.7 开发一个 ASP.NET MVC 5 应用程序。

我想根据模型的属性值禁用表格上的某些输入字段。我用javascript做到了:

if ($('#LawId').val() === "1") { 
    $('#productsTable').attr("disabled", true);
    $('.addLevelButton').attr("disabled", true);
    $('.deleteLevelButton').attr("disabled", true);
}

这很好用,但我不知道如何禁用不显眼的验证。剃刀视图是:

<td>
    <div class="group">
        @Html.TextBoxFor(m => m.Products[index].Name, new { @class = "productClass" })<br />
        <div class="mensajeError">@Html.ValidationMessageFor(m => m.Products[index].Name)</div>
    </div>
</td>
<td>
    <div class="group">
        @Html.TextBoxFor(m => m.Products[index].Description, new { @class = "productClass", @style = "max-width:none" })<br />
        <div class="mensajeError">@Html.ValidationMessageFor(m => m.Products[index].Description)</div>
    </div>
</td>
<td>
    <div class="group">
        @Html.TextBoxFor(m => m.Products[index].Comment, new { @class = "productClass" })<br />
        <div class="mensajeError">@Html.ValidationMessageFor(m => m.Products[index].Comment)</div>
    </div>
</td>
<td>
    <div class="group">
        @Html.CheckBox(string.Format("Delete_{0}", index))
    </div>
</td>

这是为我要隐藏的字段生成的 HTML(所有字段都在 productsTable 表中)。

<div class="group">
    <input data-val="true" data-val-number="The field Id must be a number." data-val-required="The Id field is required." id="Products_0__Id" name="Products[0].Id" type="hidden" value="0" />
    <input data-val="true" data-val-number="The field Law must be a number." data-val-required="The Law field is required." id="Products_0__Law" name="Products[0].Law" type="hidden" value="1" />
    <input data-val="true" data-val-length="Must be 14 characters long" data-val-length-max="14" data-val-length-min="14" data-val-required="Product&#39;s code is requiered" id="Products_0__ProductCode" name="Products[0].ProductCode" type="number" value="" />
    <div class="mensajeError"><span class="field-validation-valid" data-valmsg-for="Products[0].ProductCode" data-valmsg-replace="true"></span></div>
</div>

搜索找到了@{ Html.EnableClientValidation(false); }的helper,但是不知道怎么用,也没有找到完整的例子。

我在 Razor 视图中根据条件执行此操作以显示输入文件:

@if (Model.LawId == 1)
{
    <input name = "ChinaCodes" id = "ChinaCodes" class="upload" type="file">
}

我是否必须对每个字段都执行相同的操作,还是可以一次对所有字段全局执行此操作?

【问题讨论】:

标签: javascript asp.net-mvc razor unobtrusive-validation


【解决方案1】:

我已经在@body 部分的开头添加了这个:

@section Body
{
    @if (Model.LawId == 1)
    {
        Html.EnableClientValidation(false);
        Html.EnableUnobtrusiveJavaScript(false);
    }

    [ ... ]
}

【讨论】:

    猜你喜欢
    • 2014-07-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-11-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多