验证具有多个控件的客户端?

时间:2016-03-28 23:17:44

标签: jquery asp.net-mvc asp.net-mvc-4

我有多选下拉列表的以下代码,但我的问题是如何显示我已添加到客户端的VM类的错误消息

ViewModel类 OrderModel

 public class OrderModel
    {
        public int Id { get; set; }
        [Required]
        public int CatId { get; set; }                
        [MinLength(1, ErrorMessage="please select an item")]
        public List<ProductModel> Products { get; set; }

        public OrderModel()
        {
            Products = new List<ProductModel>();
        }
    }

ProductModel

 public class ProductModel
    {
        public int Id { get; set; }

        [Required]
        public string ProdName { get; set; }
    }

类别模型

 public class CategoryModel
    {
        public int Id { get; set; }

        [Required]
        public string CategoryName { get; set; }
    }

控制器的操作主页

 public ActionResult Create()
 {
     return View();
 }


[HttpPost]
public ActionResult Create(OrderModel order)
{
            try
            {
                // TODO: Add insert logic here
                if (ModelState.IsValid)
                {
                    //write code here
                }
                else 
                {
                    ModelState.AddModelError("", "Model error");
                }


                return RedirectToAction("Create");
            }
            catch
            {
                return View();
            }
}

视图

@model Selectmany_test.Models.OrderModel

@{  

    ViewBag.Title = "Create";
}

<h2>Create</h2>

@using (Html.BeginForm("", "", FormMethod.Post, new  { id="frm" }))
{ 
    <fieldset>
        <label>Product Categories</label>
        <select id="prodcats"></select>
        @Html.ValidationMessageFor(x=>x.CatId)
    </fieldset>
    <fieldset>
        <label>Products</label>
        <select id="prods" multiple="multiple"></select>
        @Html.ValidationMessageFor(x => x.Products)
    </fieldset>    
    <fieldset>
        <input type="submit" name="" value="Send" id="btnSend" />
    </fieldset>
}


@section Scripts{
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<link href="http://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.0.3/css/bootstrap.min.css" rel="stylesheet" type="text/css" />
<script type="text/javascript" src="http://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.0.3/js/bootstrap.min.js"></script>
<link href="http://cdn.rawgit.com/davidstutz/bootstrap-multiselect/master/dist/css/bootstrap-multiselect.css" rel="stylesheet" type="text/css" />
<script src="http://cdn.rawgit.com/davidstutz/bootstrap-multiselect/master/dist/js/bootstrap-multiselect.js" type="text/javascript"></script>
<script src="~/Scripts/jquery.unobtrusive-ajax.js"></script>
<script src="~/Scripts/jquery.validate.js"></script>
<script src="~/Scripts/jquery.validate.unobtrusive.js"></script>
@*<script src="~/Scripts/bootstrap.js"></script>*@
<script src="http://cdn.rawgit.com/davidstutz/bootstrap-multiselect/master/dist/js/bootstrap-multiselect.js"  type="text/javascript"></script>

    <script>
        $(document).ready(function () {
            var form = $('#frm');
            $('#prods').multiselect({ includeSelectAllOption: true });

            $('#btnSend').click(function () {

                if (form.valid())
                {
                    //ajax to call Create() to save but how do i make the form invalid if the user failed to select one from multi-select dropdown
                }
            });


        $.ajax({    
            url:'@Url.Action("GetCategories","Home")',
            method:'get',
            dataType:'json',
            success: function (data) {
                $('#prodcats').empty();
                $('#prodcats').append('<option>select fruit</option>');
                $(data).each(function (index, item) {                    
                    $('#prodcats').append( $('<option />', {text:item.CategoryName, value:item.Id}) );
                })
                $('#prods').empty();
                $('#prods').append('<option>Select product</option>');
                $('#prods').prop({ disabled: true });
            },
            error: function(x,y,z){
                alert('error');
            }    
        });

        $('#prodcats').change(function (evt) {
            var x = $(this).val();
            console.log(x);
            if (x == 'select fruit')
            {
                $('#prods').empty();
                $('#prods').append('<option>select product</option>');
                $('#prods').prop({ disabled: true });
            }
            else
            {
                $('#prods').empty();
                $('#prods').append('<option>select product</option>');
                $('#prods').prop({ disabled: false });
                var Id = $('#prodcats').val();

                $.ajax({
                    url: '@Url.Action("GetProductsByCatId", "Home")',
                    method: 'GET',
                    contentType: 'application/json; charset=utf-8',
                    data: JSON.Stringgyfy({ 'catId': Id }),
                    dataType: 'json',
                    success: function (data) {
                        console.log(data);
                        $(data).each(function (index, item) {
                            $('#prods').append($('<option />', { text:item.ProdName, value:item.Id}));
                        });
                    },
                    error: function (x,y,z) { }
                });
            }
        });

    });
    </script>
    }

所有ajax get方法都有效但如果表单无效,如何停止save方法调用。如果用户未能选择类别并从多选“prods”中选择至少一个,表单将变为无效,如前所述,我想显示模型错误消息“请选择一个项目”

0 个答案:

没有答案