動的ドロップダウン リストからの選択を表すためのエディター テンプレートを作成しましたが、確認できなかった検証以外は正常に機能します。モデルに[Required]
属性が設定されている場合、デフォルトのオプションが選択されている場合は無効にします。
ドロップダウン リストとして表す必要があるビュー モデル オブジェクトは次のSelector
とおりです。
public class Selector
{
public int SelectedId { get; set; }
public IEnumerable<Pair<int, string>> Choices { get; private set; }
public string DefaultValue { get; set; }
public Selector()
{
//For binding the object on Post
}
public Selector(IEnumerable<Pair<int, string>> choices, string defaultValue)
{
DefaultValue = defaultValue;
Choices = choices;
}
}
エディター テンプレートは次のようになります。
<%@ Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl" %>
<select class="template-selector" id="<%= ViewData.ModelMetadata.PropertyName %>.SelectedId" name="<%= ViewData.ModelMetadata.PropertyName %>.SelectedId">
<%
var model = ViewData.ModelMetadata.Model as QASW.Web.Mvc.Selector;
if (model != null)
{
%>
<option><%= model.DefaultValue %></option><%
foreach (var choice in model.Choices)
{
%>
<option value="<%= choice.Value1 %>"><%= choice.Value2 %></option><%
}
}
%>
</select>
次のようなビューから呼び出すことで、機能するようになりました(どこCategory
に a がありますSelector
):
<%= Html.ValidationMessageFor(n => n.Category.SelectedId)%>
しかし、適切な番号を指定していないという検証エラーが表示され、Required
属性を設定してもかまいません。