【发布时间】:2013-07-26 08:15:45
【问题描述】:
我被推荐到这个帖子article stackoverflow 还有这个second article stackoverflow
我正在使用 RadioButtonListFor
public static MvcHtmlString RadioButtonListFor<TModel, TProperty>(
this HtmlHelper<TModel> htmlHelper,
Expression<Func<TModel, TProperty>> expression,
IEnumerable<SelectListItem> listOfValues,
IDictionary<string, object> radioHtmlAttributes = null,
string ulClass = null)
{
ModelMetadata metaData = ModelMetadata.FromLambdaExpression(expression, htmlHelper.ViewData);
if (radioHtmlAttributes == null)
radioHtmlAttributes = new RouteValueDictionary();
TagBuilder ulTag = new TagBuilder("ul");
if (!String.IsNullOrEmpty(ulClass))
ulTag.MergeAttribute("class", ulClass);
if (listOfValues != null)
{
// Create a radio button for each item in the list
foreach (SelectListItem item in listOfValues)
{
// Generate an id to be given to the radio button field
var id = string.Format("{0}_{1}", metaData.PropertyName, item.Value);
if (!radioHtmlAttributes.ContainsKey("id"))
radioHtmlAttributes.Add("id", id);
else
radioHtmlAttributes["id"] = id;
// Create and populate a radio button using the existing html helpers
var label = htmlHelper.Label(id, HttpUtility.HtmlEncode(item.Text));
var radio = htmlHelper.RadioButtonFor(expression, item.Value, radioHtmlAttributes).ToHtmlString();
// Create the html string that will be returned to the client
// e.g. <input data-val="true" data-val-required="You must select an option" id="TestRadio_1" name="TestRadio" type="radio" value="1" /><label for="TestRadio_1">Line1</label>
ulTag.InnerHtml += string.Format("<li>{0}{1}</li>", radio, label);
}
}
return MvcHtmlString.Create(ulTag.ToString(TagRenderMode.Normal));
}
我的问题是单选按钮是必需的,当我不检查单选按钮时,我有一个错误,该字段是强制性的,我该如何禁用它? (在我的视图模型中,我不使用必需的 dataAnnotation)
这是我的 viewModel 的一部分:
public class RegistrationViewModel
{
#region country
public string Country { get; set; }
private string CountryLabel { get; set; }
public ConfigurationParamValue CountryParam { get; set; }
#endregion
#region civilty
public int Civility { get; set; }
public ConfigurationParamValue CivilityParam { get; set; }
public string CivilityLabel { get; set; }
public List<Civility> ListCivilitys { get; set; }
#endregion
}
这是我观点的一部分:
<div id="city">
<div class="editor-label" style="@visibleCivility">
@Html.GetResource(Model.Category,Model.IsLocal,Constantes.CivilityLabel)
<div style="@mandatoryCivility">*</div>
</div>
<div class="editor-field">
@Html.RadioButtonListFor(m => m.Civility, new SelectList(Model.ListCivilitys,"ID","Name"))
@Html.ValidationMessageFor(model => model.Civility)
</div>
</div>
【问题讨论】:
-
你能显示模型类的定义吗?
-
您可能有一个必填字段验证器?
-
我编辑了问题以添加一些详细信息,我没有使用所需的验证器
-
也许你的控制器中有验证逻辑?
-
我的控制器中没有有效的逻辑,问题是新助手创建的 html 包含:
<input data-val="true" data-val-number="Le champ Civility doit être un nombre." data-val-required="The Civility field is required." id="Civility_1" name="Civility" type="radio" value="1" />而我没有使用必需的属性
标签: c# asp.net-mvc validation razor data-annotations