使用asp.net mvc中的单选按钮进行远程验证

mar*_*dok 3 asp.net-mvc jquery jquery-validate

我需要在我的布尔字段上使用远程验证.我有看起来像这样的模型:

public class ViewModel
{   
    [Remote("ValidMePlease", "Home", AdditionalFields = "SomeKindOfDate", ErrorMessage = "use date with true")]
    public bool IsSomething {get;set;}
    public DateTime? SomeKindOfDate {get;set;}
}
Run Code Online (Sandbox Code Playgroud)

我的控制器:

[OutputCache(Location = System.Web.UI.OutputCacheLocation.None, NoStore = true)]
public class HomeController : Controller 
{
    public JsonResult ValidMePlease(bool IsSomething , DateTime? SomeKindOfDate )
    {
        if (IsSomething && !SomeKindOfDate .HasValue)
            return Json(false, JsonRequestBehavior.AllowGet);
        return Json(true, JsonRequestBehavior.AllowGet);
    }
}
Run Code Online (Sandbox Code Playgroud)

我的看法:

<div class="control">
    @Html.LabelFor(m => m.IsSomething , new { @class = "control-label" })
    <div class="controls">
        <label class="radio inline">
            @Html.RadioButtonFor(m => m.IsSomething , false) No
        </label>
        <label class="radio inline">
            @Html.RadioButtonFor(m => m.IsSomething, true) Yes
        </label>
    </div>
</div>
Run Code Online (Sandbox Code Playgroud)

我呈现的视图:

   <div class="control">
        <label class="control-label" for="IsSomething ">Is something</label>
        <div class="controls">
            <label class="radio inline">
                <input checked="checked" data-val="true" data-val-remote="use date with true" data-val-remote-additionalfields="*.IsSomething ,*.SomeKindOfDate" data-val-remote-url="/admin/User/ValidMePlease" data-val-required="Is something is required." id="IsSomething " name="IsSomething " type="radio" value="False" /> No
            </label>
            <label class="radio inline">
                <input id="IsSomething " name="IsSomething " type="radio" value="True" /> Yes
            </label>
        </div>
</div>
Run Code Online (Sandbox Code Playgroud)

想法是当布尔字段为真时我需要一个日期.那是什么问题.当我提交的形式,它总是通过falseIsSomething在我的ValidMePlease远程方法.我认为这是因为只有第一个输入才有data-val-属性.任何建议将不胜感激.

Sta*_*kas 5

看起来"远程"验证器中的jquery.validate.unobtrusive.js中存在错误.尝试更换此行:

return $(options.form).find(":input[name='" + escapeAttributeValue(paramName) + "']").val();
Run Code Online (Sandbox Code Playgroud)

有:

var $input = $(options.form).find(":input[name='" + escapeAttributeValue(paramName) + "']");
if ($input.is(":radio")) {
    return $input.filter(":checked").val();
} else {
    return $input.val();
}
Run Code Online (Sandbox Code Playgroud)

在两个单选按钮上都需要相同的验证器,以确保选择"是"选项时字段有效.

另一件小事是确保你的HTML中id是唯一的.在您的示例中,您有两个具有相同id属性的单选按钮.我会用这样的东西:

@Html.RadioButtonFor(m => m.IsSomething, false, new { id = "IsSomething_False" })
@Html.RadioButtonFor(m => m.IsSomething, true, new { id = "IsSomething_True" })
Run Code Online (Sandbox Code Playgroud)

补充:验证应该在不更改id属性的情况下工作.

ID的定义必须在任何系统中都是唯一的,因此通过确保它是唯一的,不仅可以帮助您验证w3c.org,还可以帮助您为每个单选按钮添加标签.