ASP.Net MVC:如何在处理多个复选框时显示验证消息

时间:2016-03-24 17:27:42

标签: jquery asp.net-mvc unobtrusive-validation asp.net-mvc-validation

我在循环中显示了许多复选框,我希望当用户提交表单时,用户必须至少选中一个复选框。如果未选中任何复选框,则验证消息将显示在客户端,并且不会提交表单。 所以这是

型号&视图模型

public class Hobby
{
    public string Name { get; set; }
    public bool IsSelected { get; set; }
}

public class SampleViewModel
{

    [Required(ErrorMessage = "Select any Hobbies")]
    public List<Hobby> Hobbies { get; set; }
}

动作方法代码

public ActionResult Index()
{
    var SampleVM = new SampleViewModel();

    SampleVM.Hobbies = new List<Hobby>()
    {
        new Hobby(){ Name = "Reading", IsSelected= false },
        new Hobby(){ Name = "Sports" ,IsSelected= false},
        new Hobby(){ Name = "Movies" ,IsSelected= false}
    };
    return View(SampleVM);
}

[HttpPost]
public ActionResult Index(SampleViewModel vm)
{
    ViewBag.IsPostBack = false;

    if (ModelState.IsValid)
    {
        Product p = vm.Products.Where(x => x.ID == vm.SelectedProductId).FirstOrDefault();
        ViewBag.IsPostBack = true;
        ViewBag.ProductID = p.ID.ToString();
        ViewBag.ProductName = p.Name.ToString();
        return View(vm);
    }
    else
    {
        var SampleVM = new SampleViewModel();
        SampleVM.Hobbies = new List<Hobby>()
        {
            new Hobby(){ Name = "Reading", IsSelected= false },
            new Hobby(){ Name = "Sports" ,IsSelected= true},
            new Hobby(){ Name = "Movies" ,IsSelected= true}
        };

        return View(SampleVM);
    }

查看代码

<div class="form-group">
    <div class="col-md-offset-2 col-md-10">
        <b>Hobbies</b><br />
        @for (int x = 0; x < Model.Hobbies.Count(); x++)
        {
            @Html.CheckBoxFor(p => p.Hobbies[x].IsSelected) @: &nbsp; 
            @Html.LabelFor(p => p.Hobbies[x].IsSelected, Model.Hobbies[x].Name) @: &nbsp;
        }
    </div>
    @Html.ValidationMessageFor(model => model.Hobbies, "", new { @class = "text-danger" })
</div>

所以请告诉我在代码中要更改的内容,如果用户没有为爱好选择复选框,则会触发验证消息。我犯了错误,或者我需要以不同的方式编码来实现这个目标?

请帮我提供示例代码。

感谢

0 个答案:

没有答案