Проверка модели не оценивает атрибуты, связанные со значениями списка, если вы не выберете хотя бы один из них.
Таким образом, невозможно выполнить оценку модели с использованием DataAnnotations для информирования о необходимых значениях.
Контроллер:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using TestValidation.Models;
namespace TestValidation.Controllers
{
[HandleError]
public class HomeController : Controller
{
private SelectList list = new SelectList(new List<string>()
{
"Sao Paulo",
"Toronto",
"New York",
"Vancouver"
});
public ActionResult Index()
{
ViewData["ModelState"] = "NOT EVAL";
ViewData["ItemsList"] = list;
return View();
}
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Index(MyEntity entity)
{
if (ModelState.IsValid)
{
ViewData["ModelState"] = "VALID";
}
else
{
ViewData["ModelState"] = "NOT VALID!!!";
}
ViewData["ItemsList"] = list;
return View();
}
public ActionResult About()
{
return View();
}
}
}
Вид:
<%@ Page Language="C#" MasterPageFile="~/Views/Shared/Site.Master" Inherits="System.Web.Mvc.ViewPage<TestValidation.Models.MyEntity>" %>
<asp:Content ID="indexTitle" ContentPlaceHolderID="TitleContent" runat="server">
Home Page
</asp:Content>
<asp:Content ID="indexContent" ContentPlaceHolderID="MainContent" runat="server">
<h2>
Validation Test</h2>
<p>
<% using (Html.BeginForm())
{%>
<fieldset>
<p>
ModelState:
<%= Html.Encode((string)ViewData["ModelState"])%>
</p>
<p>
<label for="Name">
Name:</label>
<%= Html.TextBoxFor(m => m.Name)%>
<%= Html.ValidationMessageFor(m => m.Name)%>
</p>
<p>
<label for="ItemFromList">
Items (list):</label>
<%= Html.ListBoxFor(m => m.ItemFromList, ViewData["ItemsList"] as SelectList)%>
<%= Html.ValidationMessageFor(m => m.ItemFromList)%>
</p>
<p>
<label for="ItemFromCombo">
Items (combo):</label>
<%= Html.DropDownListFor(m => m.ItemFromCombo, ViewData["ItemsList"] as SelectList)%>
<%= Html.ValidationMessageFor(m => m.ItemFromCombo)%>
</p>
<p>
<input type="submit" value="Submit" />
</p>
</fieldset>
<% } %>
</asp:Content>
Модель:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.ComponentModel.DataAnnotations;
namespace TestValidation.Models
{
public class MyEntity_Validate : ValidationAttribute
{
public MyEntity_Validate()
{
this.ErrorMessage = "Validated!. Is <> Toronto";
}
public override bool IsValid(object value)
{
return ((string)value == "Toronto");
}
}
public class MyEntity
{
[Required]
public string Name { get; set; }
[MyEntity_Validate]
public string ItemFromList { get; set; }
[MyEntity_Validate]
public string ItemFromCombo { get; set; }
}
}
Любая помощь будет принята с благодарностью. Спасибо.