加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > asp.Net > 正文

asp.net-mvc – 使用数据注释验证ASP.NET MVC 2中的SelectList

发布时间:2020-12-16 07:08:19 所属栏目:asp.Net 来源:网络整理
导读:我正在尝试在选择列表上使用内置的ASP.NET MVC 2客户端验证,如下所示: private SelectList _CategoryList; [Required(ErrorMessage = "Category Required")] [System.ComponentModel.DataAnnotations.Range(1,double.MaxValue,ErrorMessage = "Please Selec
我正在尝试在选择列表上使用内置的ASP.NET MVC 2客户端验证,如下所示:

private SelectList _CategoryList;
        [Required(ErrorMessage = "Category Required")]
        [System.ComponentModel.DataAnnotations.Range(1,double.MaxValue,ErrorMessage = "Please Select A Category")]
        [DisplayName("Category")]
        public SelectList CategoryList
        {
            get
            {
                return new SelectList(Categories,"CatID","CatFullName"); ;
            }
            set
            {
                _CategoryList = value;
            }
        }

但是它不起作用…如果选择了默认值0,则不会出现验证消息,并且页面会像验证一样进行.思考?

解决方法

好的,我在一个稍微不同的问题的答案中找到了答案.所以我在这里发布我的完整代码,它扩展了Scott Guthries ASP.NET MVC 2验证帖子: http://weblogs.asp.net/scottgu/archive/2010/01/15/asp-net-mvc-2-model-validation.aspx

我的ViewModel:

public class Person
{
    [Required(ErrorMessage="First Name Required")]
    [StringLength(50,ErrorMessage="Must be under 50 characters")]
    public string FirstName { get; set; }

    [Required(ErrorMessage="Last Name Required")]
    [StringLength(50,ErrorMessage = "Must be under 50 characters")]
    public string LastName { get; set; }

    [Required(ErrorMessage="Age Required")]
    [Range(1,120,ErrorMessage="Age Must be between 0 and 120")]
    public int Age { get; set; }

    [Required(ErrorMessage="Email Required")]
    public string Email { get; set; }


    public IEnumerable<SelectListItem> FavoriteColor { get; set; }


    [Range(0,6,ErrorMessage = "Out of range")]
    public int SelectedFavColor { get; set; }
}

我的颜色类:

public class Colors
{
    public int ColorID { get; set; }
    public string ColorName { get; set; }
}

我的名单助手扩展程序是从Rob Connery那里偷来的,他从别人那里偷了它:

public static class ListExtensions
{
    public static IEnumerable<T> ForEach<T>(this IEnumerable<T> collection,Action<T> action)
    {
        foreach (var item in collection) action(item);
        return collection;
    }

    public static SelectList ToSelectList<T>(this IEnumerable<T> collection)
    {
        return new SelectList(collection,"Key","Value");
    }

    public static SelectList ToSelectList<T>(this IEnumerable<T> collection,string selectedValue)
    {
        return new SelectList(collection,"Value",selectedValue);
    }

    public static SelectList ToSelectList<T>(this IEnumerable<T> collection,string dataValueField,string dataTextField)
    {
        return new SelectList(collection,dataValueField,dataTextField);
    }

    public static SelectList ToSelectList<T>(this IEnumerable<T> collection,string dataTextField,dataTextField,selectedValue);
    }
}

我的控制器代码(是的,它可以被重构为更干):

public ActionResult Create()
    {
        Person newFriend = new Person();
        IList<Colors> colorslist = new List<Colors>();
        colorslist.Add(new Colors { ColorID = -1,ColorName = "Please Select Color" });
        colorslist.Add(new Colors { ColorID = 1,ColorName = "Red" });
        colorslist.Add(new Colors { ColorID = 2,ColorName = "Green" });
        colorslist.Add(new Colors { ColorID = 3,ColorName = "Blue" });

        newFriend.FavoriteColor = colorslist.ToSelectList("ColorID","ColorName","-1");
        return View(newFriend);
    }

    [HttpPost]
    public ActionResult Create(Person friendToCreate,FormCollection collection)
    {
        friendToCreate.SelectedFavColor = Convert.ToInt32(collection["SelectedFavColor"]);
        if (ModelState.IsValid)
        {
            return Redirect("/");
        }
        IList<Colors> colorslist = new List<Colors>();
        colorslist.Add(new Colors { ColorID = -1,ColorName = "Blue" });
        friendToCreate.FavoriteColor = colorslist.ToSelectList("ColorID","ColorName");
        return View(friendToCreate);
    }

我的页面标记:

<% using (Html.BeginForm()) {%>

    <fieldset>
        <legend>Fields</legend>

        <div class="editor-label">
            <%= Html.LabelFor(model => model.FirstName) %>
        </div>
        <div class="editor-field">
            <%= Html.TextBoxFor(model => model.FirstName) %>
            <%= Html.ValidationMessageFor(model => model.FirstName) %>
        </div>

        <div class="editor-label">
            <%= Html.LabelFor(model => model.LastName) %>
        </div>
        <div class="editor-field">
            <%= Html.TextBoxFor(model => model.LastName) %>
            <%= Html.ValidationMessageFor(model => model.LastName) %>
        </div>

        <div class="editor-label">
            <%= Html.LabelFor(model => model.Age) %>
        </div>
        <div class="editor-field">
            <%= Html.TextBoxFor(model => model.Age) %>
            <%= Html.ValidationMessageFor(model => model.Age) %>
        </div>

        <div class="editor-label">
            <%= Html.LabelFor(model => model.Email) %>
        </div>
        <div class="editor-field">
            <%= Html.TextBoxFor(model => model.Email) %>
            <%= Html.ValidationMessageFor(model => model.Email) %>
        </div>

        <div class="editor-label">
            <%= Html.LabelFor(model => model.FavoriteColor) %>
        </div>
        <div class="editor-field">
            <%= Html.DropDownList("SelectedFavColor",Model.FavoriteColor,-1)%>
            <%= Html.ValidationMessageFor(model => model.SelectedFavColor) %>
        </div>

        <p>
            <input type="submit" value="Submit" />
        </p>
    </fieldset>

<% } %>

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读