目前我有一个带文本框和ValidationMessageFor的局部视图。这工作正常,当输入无效时,消息显示为预期。我正在进行一些HTML重构,我想将validationMessageFor提升到当前包含局部视图的视图。我几乎让它正常工作,但有一些障碍。
@Html.ValidationMessageFor(m => m.Mileage, string.Empty, new { id = "spanMileageError", @class = "mileageErrorSpanClass" })
此视图的模型是车辆对象。 partialView的模型是一个稍微不同的对象
@Html.TextBoxFor(v => v.Vehicle.Mileage, new { placeHolder = mileagePlaceHolderText, id = Model.TextBoxId, maxlength = "7", @class="mileageTextBoxClass" })
此配置给出了文本框的名称(“Vehicle.Mileage”),但Validation属性(“data-valmsg-for”)等于“Mileage”而不是“Vehicle.Mileage”。
如何更正ValidationMessageFor助手以发出正确的HTML以使此验证有效?
以下是HTML重构之前的当前视图的呈现HTML
<input type="text" value="" placeholder="Enter Mileage" name="Vehicle.Mileage" maxlength="7" id="textBoxMileage" data-val-range-min="1" data-val-range-max="999999" data- val-range="Mileage must be a valid number between 1 and 999,999." data-val-number="The field Mileage must be a number." data-val="true" class="mileageTextBoxClass input- validation-error" autocomplete="off">
<span id="spanMileageError" data-valmsg-replace="true" data-valmsg-for="Vehicle.Mileage" class="mileageErrorSpanClass field-validation-error"><span htmlfor="textBoxMileage" generated="true" class="">Mileage must be a valid number between 1 and 999,999.</span></span>
这是重构后的HTML
<input type="text" value="" placeholder="Enter Mileage" name="Vehicle.Mileage" maxlength="7" id="textBoxMileage" data-val-range-min="1" data-val-range-max="999999" data-val-range="Mileage must be a valid number between 1 and 999,999." data-val-number="The field Mileage must be a number." data-val="true" class="mileageTextBoxClass placeholder" autocomplete="off">
<span id="spanMileageError" data-valmsg-replace="true" data-valmsg-for="Mileage" class="field-validation-valid mileageErrorSpanClass"></span>
请注意,span缺少以前存在的内部span元素。任何人都可以帮我纠正这个问题吗?
感谢您提供任何提示和技巧或可能的解决方案。
干杯,
〜在圣地亚哥
答案 0 :(得分:1)
您可以使用Html.TextBox()代替
@Html.TextBox("Mileage", Model.Vehicle.Mileage, new { placeHolder = mileagePlaceHolderText, id = Model.TextBoxId, maxlength = "7", @class="mileageTextBoxClass" })
答案 1 :(得分:0)
我对MVC有点新,但为什么不使用相同的型号呢?像这样:
@model ProjectNamespace.Models.Vehicle
或者像这样:
@using ProjectNamespace.Models.Vehicle
我猜你可以达到你想要的效果。