ASP.NET MVC数据验证 - 高亮表格行还是文本框

4
在ASP.NET MVC视图上,我有几个复选框,一个用于电子邮件地址,另一个用于电话。我想确保至少一个被选中(两个都可以被选中,因此单选按钮不是理想的选择),如果两个都没有被选中,则像文本框的验证功能一样,突出显示带有红色边框的行...
我的其他字段正在得到正确的验证,并且CSS会相应地更改当文本框和文本区域存在问题时。下面的代码显示了通知用户必须指定联系人首选项的消息,但没有将行突出显示为有问题...
屏幕截图: alt text 视图:
<table width="100%">
    <tr>
        <td>
            <label>
                How would you like us to contact you?
            </label>
        </td>
    </tr>
    <tr id="pref_row">
        <td>
            <span class="bold-text">Email: </span>&nbsp;
            <%=Html.CheckBox("EmailDesired")%>
            &nbsp; &nbsp; <span class="bold-text">Phone: </span>&nbsp;
            <%=Html.CheckBox("PhoneDesired")%>
        </td>
    </tr>
</table>

控制器

[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Index(ContactUs contactus)
{
    ContactUsService svc = new ContactUsService();
    // Validation
    if (!contactus.EmailDesired && !contactus.PhoneDesired)
        ViewData.ModelState.AddModelError("pref_row", "Please specify a contact preference (phone and/or email)!");

    if (ViewData.ModelState.IsValid)
    {
        MessageModel msg = svc.SendRequest(contactus);
        return RedirectToAction("Index", msg);
    }
    else
    {
        return View();
    }
}

丹尼尔 - 必须勾选一个,但也可以同时勾选两个。 单选按钮通常用于A或B中的一个,而不是A和B的两个都选择... - RSolberg
1个回答

4
当HtmlHelper自身呈现时,它会检查ModelState字典中是否有与Helper本身相同的键。如果有,则控件将呈现为属性类等于“input-validation-error”,该属性在css文件中定义。
因此,样式仅适用于已呈现的输入控件。
这是我的解决方案:
<table width="100%">
    <tr>
        <td>
            <label>
                How would you like us to contact you?
            </label>
        </td>
    </tr>
    <tr class="<%=ViewData.ModelState["pref_row"]!= null ? "input-validation-error":"" %>">
        <td>
            <span class="bold-text">Email: </span> 
            <%=Html.CheckBox("EmailDesired")%>
                <span class="bold-text">Phone: </span> 
            <%=Html.CheckBox("PhoneDesired")%>
        </td>
    </tr>
</table>

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接