MVC3 client validation not working

前端 未结 3 1460
借酒劲吻你
借酒劲吻你 2021-01-05 11:39

I have a required annotation on my model:

[Required(ErrorMessage = \"Please choose an option\")]
public bool? AnyDebts { get; set; }

I have

3条回答
  •  清酒与你
    2021-01-05 12:06

    
    
    
    

    are the only required scripts for client validation to work.

    And as always here's a full working demo:

    Model:

    public class MyViewModel
    {
        [Required(ErrorMessage = "Please choose an option")]
        public bool? AnyDebts { get; set; }
    }
    

    Controller:

    public class HomeController : Controller
    {
        public ActionResult Index()
        {
            return View(new MyViewModel());
        }
    
        [HttpPost]
        public ActionResult Index(MyViewModel model)
        {
            return View(model);
        }
    }
    

    View:

    @model AppName.Models.MyViewModel
    @{
        ViewBag.Title = "Home Page";
    }
    
    
    @using (Html.BeginForm())
    {
        
    Debts
    Yes @Html.RadioButtonFor(x => x.AnyDebts, true) No @Html.RadioButtonFor(x => x.AnyDebts, false) @Html.ValidationMessageFor(x => x.AnyDebts) }

    Remark: I haven't included jquery-1.4.4.js in my view because it is already referenced in the layout.

提交回复
热议问题