我的视图中有单选按钮列表,如下所示..
看法:
<div class="deleteControls">
<div class="labelHead">@Html.Label("Delete")</div>
<div class="controlsAndLabels">@Html.RadioButtonFor(m => m.Submit, MVC.Models.SubmitAction.DeleteItem) @Html.Label("Delete By Item")</div>
<div class="controlsAndLabels">@Html.RadioButtonFor(m => m.Submit, MVC.Models.SubmitAction.DeleteVendor) @Html.Label("Delete By Vendor")</div>
<div class="controlsAndLabels" style="padding-left: 20px;">@Html.CheckBoxFor(m => m.IsCancelPageChecked, "Cancel Page") @Html.Label("Cancel Page")</div>
<div class="controlsAndLabels">@Html.RadioButtonFor(m => m.Submit, MVC.Models.SubmitAction.DeleteMember) @Html.Label("Delete By Member")</div>
</div>
这是我为单选按钮定义属性的视图模型
模型:
public SubmitAction Submit { get; set; }
public bool IsCancelPageChecked { get; set; }
[DeleteByItemValidator("ByItem")]
[Display(Name = "By Item")]
public string ByItem { get; set; }
[Display(Name = "By Vendor")]
public string ByVendor { get; set; }
[Display(Name = "By Member")]
public string ByMember { get; set; }
[Display(Name = "Cancel Page")]
public string CancelPage { get; set; }
这个枚举用于绑定单选按钮列表
public enum SubmitAction
{
DeleteItem,
DeleteVendor,
DeleteMember
}
我正在使用自定义验证器在服务器端进行自定义验证,如下所示
public class DeleteByItemValidator : ValidationAttribute
{
public string DeleteByItemRadioButton { get; set; }
public DeleteByItemValidator(string deleteByItemRadioButton)
{
this.DeleteByItemRadioButton = deleteByItemRadioButton;
}
protected override ValidationResult IsValid(object currentValue, ValidationContext validationContext)
{
if (IsRadionButtonSelected(validationContext, DeleteByItemRadioButton))
{
// here I am doing validaions
}
return ValidationResult.Success;
}
// this method is giving always false even if i selected one radio button
private bool IsRadionButtonSelected(ValidationContext validationContext, string PropertyToSelect)
{
Type iType = validationContext.ObjectInstance.GetType();
object RadioButtonSelectedValue = iType.GetProperty(PropertyToSelect).GetValue(validationContext.ObjectInstance, null);//here I am getting null value
bool isChecked = Convert.ToBoolean(RadioButtonSelectedValue);
return isChecked;
}
}
我的问题是我没有检查是否选择了单选按钮,即使我选择了单选按钮,此方法也会返回错误值
private bool IsRadionButtonSelected(ValidationContext validationContext, string PropertyToSelect)`
这种方式是否正确验证单选按钮选择或者是否有任何其他方法请提出任何想法。
有人知道如何检查单选按钮是否被选中
提前谢谢了