asp.net-mvc - 如何将 Html.CheckBox(列表)与 IEnumerable<T> 一起使用并进行验证

标签 asp.net-mvc validation model-validation

我正在开发一个页面,用户需要填写一些信息,最后通过复选框选择 1 个或多个客户。

客户列表是IEnumerable<Customer>我将其传递到我的模型中。我将如何使用 .CheckBoxFor() 创建复选框列表?

最后,我希望能够验证是否至少选中了 1 个复选框。

Request 是保存用户输入的信息的对象。

<% foreach (var customer in Model.Request.Customers) { %>
   <%= Html.CheckBoxFor(/* customer */) %>
<% } %>

有人能指出我正确的方向吗?还是我的做法完全错了?

最佳答案

您可以创建一个自定义 html 扩展类并重载 CheckBoxFor 方法,如下所示。该方法将metadata.Model 评估为传递给它的值(例如美国州)。您可以从 ControllerAction 中的 FormCollection 获取复选框值:

public ActionResult Edit(FormCollection formCollection) 
{
    // Get the value(s)
    string checkBox = formCollection["State"];

    // perform validation
    ....
}

示例假设有一个键值对通用列表

<% foreach (var element in UnitedStatesDictionary())
{ %>
<%= Html.CheckBoxFor(model => model.State, null, element.Key) %><%= element.Value  %><br />
<% } %>

HtmlExtensions.cs

using System;
using System.Linq;
using System.Linq.Expressions;
using System.Web.Mvc;
using System.Web.Routing;

    public static class HtmlExtensions
    {
        /// <summary>
        /// Checks the box for.
        /// </summary>
        /// <typeparam name="TModel">The type of the model.</typeparam>
        /// <typeparam name="TValue">The type of the value.</typeparam>
        /// <param name="html">The HTML.</param>
        /// <param name="expression">The expression.</param>
        /// <returns>Checkbox</returns>
        public static MvcHtmlString CheckBoxFor<TModel, TValue>(this HtmlHelper<TModel> html, Expression<Func<TModel, TValue>> expression)
        {
            return CheckBoxFor(html, expression, new RouteDirection());
        }


        /// <summary>
        /// Checks the box for.
        /// </summary>
        /// <typeparam name="TModel">The type of the model.</typeparam>
        /// <typeparam name="TValue">The type of the value.</typeparam>
        /// <param name="html">The HTML.</param>
        /// <param name="expression">The expression.</param>
        /// <param name="htmlAttributes">The HTML attributes.</param>
        /// <returns>Checkbox</returns>
        public static MvcHtmlString CheckBoxFor<TModel, TValue>(this HtmlHelper<TModel> html, Expression<Func<TModel, TValue>> expression, object htmlAttributes)
        {

            return CheckBoxFor(html, expression, htmlAttributes, "");
        }

        /// <summary>
        /// Checks the box for.
        /// </summary>
        /// <typeparam name="TModel">The type of the model.</typeparam>
        /// <typeparam name="TValue">The type of the value.</typeparam>
        /// <param name="html">The HTML.</param>
        /// <param name="expression">The expression.</param>
        /// <param name="htmlAttributes">The HTML attributes.</param>
        /// <param name="checkedValue">The checked value.</param>
        /// <returns>Checkbox</returns>
        public static MvcHtmlString CheckBoxFor<TModel, TValue>(this HtmlHelper<TModel> html, Expression<Func<TModel, TValue>> expression, object htmlAttributes, string checkedValue)
        {

            ModelMetadata metadata = ModelMetadata.FromLambdaExpression(expression, html.ViewData);
            string htmlFieldName = ExpressionHelper.GetExpressionText(expression);

            TagBuilder tag = new TagBuilder("input");
            tag.Attributes.Add("type", "checkbox");
            tag.Attributes.Add("name", metadata.PropertyName);
            if (!string.IsNullOrEmpty(checkedValue))
            {
                tag.Attributes.Add("value", checkedValue);
            }
            else
            {
                tag.Attributes.Add("value", metadata.Model.ToString());
            }

            if (htmlAttributes != null)
            {
                tag.MergeAttributes(new RouteValueDictionary(htmlAttributes));
            }

            if (metadata.Model.ToString() == checkedValue)
            {
                tag.Attributes.Add("checked", "checked");
            }
            return MvcHtmlString.Create(tag.ToString(TagRenderMode.SelfClosing));
        }
    }

当我这样做时,这是我要完成代码的美国列表:

/// <summary>
/// United States dictionary.
/// </summary>
/// <returns>List of United States</returns>
public static List<KeyValuePair<string, string>> UnitedStatesDictionary()
{
    var arrList = new List<KeyValuePair<string, string>>();
    arrList.Add(new KeyValuePair<string, string>("AL", "Alabama"));
    arrList.Add(new KeyValuePair<string, string>("AK", "Alaska"));
    arrList.Add(new KeyValuePair<string, string>("AZ", "Arizona" ));
    arrList.Add(new KeyValuePair<string, string>("AR", "Arkansas" ));
    arrList.Add(new KeyValuePair<string, string>("CA", "California" ));
    arrList.Add(new KeyValuePair<string, string>("CO", "Colorado" ));
    arrList.Add(new KeyValuePair<string, string>("CT", "Connecticut" ));
    arrList.Add(new KeyValuePair<string, string>("DE", "Delaware" ));
    arrList.Add(new KeyValuePair<string, string>("DC", "District Of Columbia" ));
    arrList.Add(new KeyValuePair<string, string>("FL", "Florida" ));
    arrList.Add(new KeyValuePair<string, string>("GA", "Georgia" ));
    arrList.Add(new KeyValuePair<string, string>("HI", "Hawaii" ));
    arrList.Add(new KeyValuePair<string, string>("ID", "Idaho" ));
    arrList.Add(new KeyValuePair<string, string>("IL", "Illinois" ));
    arrList.Add(new KeyValuePair<string, string>("IN", "Indiana" ));
    arrList.Add(new KeyValuePair<string, string>("IA", "Iowa" ));
    arrList.Add(new KeyValuePair<string, string>("KS", "Kansas" ));
    arrList.Add(new KeyValuePair<string, string>("KY", "Kentucky" ));
    arrList.Add(new KeyValuePair<string, string>("LA", "Louisiana" ));
    arrList.Add(new KeyValuePair<string, string>("ME", "Maine" ));
    arrList.Add(new KeyValuePair<string, string>("MD", "Maryland" ));
    arrList.Add(new KeyValuePair<string, string>("MA", "Massachusetts" ));
    arrList.Add(new KeyValuePair<string, string>("MI", "Michigan" ));
    arrList.Add(new KeyValuePair<string, string>("MN", "Minnesota" ));
    arrList.Add(new KeyValuePair<string, string>("MS", "Mississippi" ));
    arrList.Add(new KeyValuePair<string, string>("MO", "Missouri" ));
    arrList.Add(new KeyValuePair<string, string>("MT", "Montana" ));
    arrList.Add(new KeyValuePair<string, string>("NE", "Nebraska" ));
    arrList.Add(new KeyValuePair<string, string>("NV", "Nevada" ));
    arrList.Add(new KeyValuePair<string, string>("NH", "New Hampshire" ));
    arrList.Add(new KeyValuePair<string, string>("NJ", "New Jersey" ));
    arrList.Add(new KeyValuePair<string, string>("NM", "New Mexico" ));
    arrList.Add(new KeyValuePair<string, string>("NY", "New York" ));
    arrList.Add(new KeyValuePair<string, string>("NC", "North Carolina" ));
    arrList.Add(new KeyValuePair<string, string>("ND", "North Dakota" ));
    arrList.Add(new KeyValuePair<string, string>("OH", "Ohio" ));
    arrList.Add(new KeyValuePair<string, string>("OK", "Oklahoma" ));
    arrList.Add(new KeyValuePair<string, string>("OR", "Oregon" ));
    arrList.Add(new KeyValuePair<string, string>("PA", "Pennsylvania" ));
    arrList.Add(new KeyValuePair<string, string>("RI", "Rhode Island" ));
    arrList.Add(new KeyValuePair<string, string>("SC", "South Carolina" ));
    arrList.Add(new KeyValuePair<string, string>("SD", "South Dakota" ));
    arrList.Add(new KeyValuePair<string, string>("TN", "Tennessee" ));
    arrList.Add(new KeyValuePair<string, string>("TX", "Texas" ));
    arrList.Add(new KeyValuePair<string, string>("UT", "Utah" ));
    arrList.Add(new KeyValuePair<string, string>("VT", "Vermont" ));
    arrList.Add(new KeyValuePair<string, string>("VA", "Virginia" ));
    arrList.Add(new KeyValuePair<string, string>("WA", "Washington" ));
    arrList.Add(new KeyValuePair<string, string>("WV", "West Virginia" ));
    arrList.Add(new KeyValuePair<string, string>("WI", "Wisconsin" ));
    arrList.Add(new KeyValuePair<string, string>("WY", "Wyoming" ));
    return arrList;
}

关于asp.net-mvc - 如何将 Html.CheckBox(列表)与 IEnumerable<T> 一起使用并进行验证,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3468795/

相关文章:

asp.net - 设计决策

jquery - 从 ajax 动态加载 HTML5 表格

asp.net-core-2.0 - 模型验证 .Net Core 2.0 Web Api 不工作

c# - 如何在 ASP.NET Core 2.1 的 API 模型中获取用户 IP 地址?

asp.net-core-2.1 - .net Core 中的 RequiredIf 条件属性

javascript - 有没有办法在代码后面访问javascript变量?

javascript - .net mvc 4应用程序-从ajax调用 Controller 中的函数

javascript - 禁用未选中的 radio 的提交按钮不工作

javascript - Angular JS | Angular 验证匹配密码

grails - 如何从输入中编写不包含一系列空格字符(' '的匹配项?