2

在我看来,我有一个搜索字段,id = searchPrimaryTrade. 必须找到并提交主要交易。

我使用 jquery 将所选交易的 id 复制到隐藏字段中;

@Html.HiddenFor(model => model.PrimaryTradeId)

如果用户未输入主要交易,则会显示错误消息。

但是,我还想做的是向搜索文本字段触发相同的验证 css 样式并在其旁边(id = searchPrimaryTrade)显示标记。*换句话说,我希望给文本框一个红色边框。

在下面的代码中,这是未输入 companyName 时发生的情况。那么我该怎么做呢?

@using (Html.BeginForm())
{
    @Html.AntiForgeryToken()
    ViewContext.FormContext.ValidationSummaryId = "valSumId";
    @Html.ValidationSummary(false, "Please fix these errors.", new Dictionary<string, object> { { "id", "valSumId" } });

    <fieldset>
        <legend>Create Subcontractor</legend>
        <p class="highlight">@ViewBag.Message</p>
        <table class="formTable">
            <tr>
                <td class="leftCell">@Html.LabelFor(model => model.Subcontractor.CompanyName) </td>
                <td class="rightCell">@Html.TextBoxFor(model => model.Subcontractor.CompanyName, new { @style = "width: 300px;" })
                @Html.ValidationMessageFor(model => model.Subcontractor.CompanyName, "*")</td>
            </tr>
            <tr>
                <td class="leftCell">@Html.LabelFor(model => model.PrimaryTrade)</td>
                <td class="rightCell"><input type="search" name="searchPrimaryTrade" id="searchPrimaryTrade" data-scd-autocomplete="@Url.Action("AutocompletePrimaryTrade", "DataService")" style = "width: 300px;" data-val="true" data-val-required="Must enter a Primary Trade" class="primaryTrade required"/>
                    <input type="button" id="ResetPrimaryTrade" value="Reset"/><br/>
                    @Html.HiddenFor(model => model.PrimaryTradeId)
                    @Html.ValidationMessageFor(model => model.PrimaryTradeId, "*")
                    Cannot find the trade? @Html.DialogFormButton("Add New Trade", Url.Action("AddTrade", "Popup"), "Add New Trade", null, Url.Action("Create"), "buttonAddNewTrade")
                </td>
            </tr>
4

1 回答 1

4

你真的不需要这个隐藏的字段。您可以简单地使用属性装饰PrimaryTradeId视图模型上的[Required]属性:

[Required]
public int? PrimaryTradeId { get; set; }

然后使用Html.TextBoxForandHtml.ValidationMessageFor助手而不是硬编码标记中的某些输入字段:

<td class="rightCell">
    @Html.TextBoxFor(
        model => model.PrimaryTradeId,
        new {
            type = "search",
            data_scd_autocomplete = Url.Action("AutocompletePrimaryTrade", "DataService"),
            style = "width: 300px;",
            @class = "primaryTrade required"
        }
    )
    <input type="button" id="ResetPrimaryTrade" value="Reset"/><br/>

    @Html.ValidationMessageFor(model => model.PrimaryTradeId, "*")

    Cannot find the trade? 
    @Html.DialogFormButton(
        "Add New Trade", 
        Url.Action("AddTrade", "Popup"), 
        "Add New Trade", 
        null, 
        Url.Action("Create"), 
        "buttonAddNewTrade"
    )
</td>

Html 助手现在将负责根据模型上的数据注释生成正确的标记并发出正确的验证属性。

于 2013-02-06T16:45:26.887 回答