模型状态有效MVC控制器

时间:2018-04-10 09:56:52

标签: c# jquery asp.net-mvc

我正在尝试在将集合传递给新数据对象时进行模型验证。示例在下面的图像中给出。

enter image description here

这里的问题在于它总是显示真实条件,即使属性被赋予数据注释。例如: -

enter image description here

以下是控制器端代码。

[HttpPost]
    public ActionResult Unscheduleditem(Items[] Items, string _Orders)
    {
        var dict = HttpUtility.ParseQueryString(_Orders);
        var json = new JavaScriptSerializer().Serialize(dict.AllKeys.ToDictionary(k => k, k => dict[k]));

        JavaScriptSerializer json_serializer = new JavaScriptSerializer();
        dynamic Odata = json_serializer.Deserialize<object>(json);

        DeliveryReceiptRepository _DeliveryReceiptRepository = new DeliveryReceiptRepository();

        _DeliveryReceiptRepository.CustomerID = (string.IsNullOrEmpty((Odata["CustomerID"])) ? 0 : int.Parse(Odata["CustomerID"]));
        _DeliveryReceiptRepository.BreakStationID = (string.IsNullOrEmpty((Odata["BreakStationID"])) ? 0 : int.Parse(Odata["BreakStationID"]));            
        _DeliveryReceiptRepository.RouteAreaID = (string.IsNullOrEmpty((Odata["RouteAreaID"])) ? 0 : int.Parse(Odata["RouteAreaID"]));
        _DeliveryReceiptRepository.UserId = (string.IsNullOrEmpty((Odata["UserId"])) ? 0 : int.Parse(Odata["UserId"]));
        _DeliveryReceiptRepository.PriorityTypeID = (string.IsNullOrEmpty((Odata["PriorityTypeID"])) ? 0 : int.Parse(Odata["PriorityTypeID"]));
        _DeliveryReceiptRepository.ShipDate = null;//(string.IsNullOrEmpty(Odata["ShipDate"]) ? null : Convert.ToDateTime(Odata["ShipDate"]));


        if(ModelState.IsValid)
        {
            return Json(new { error = 0, massage = "Unscheduled Item/Order Created successfully" });
        }
        else
        {
            return Json(new { error = 1, massage = "Unscheduled Item/Order Created successfully" });
        }
    }

以下是下面给出的业务层边码。

public class DeliveryReceiptRepository
{
    public int DeliveryReceiptIDNumber { get; set; }
    [Range(1, int.MaxValue)]
    [Required(ErrorMessage = "Please Select Break Station")]
    public int BreakStationID { get; set; }
    [Range(1, int.MaxValue)]
    [Required(ErrorMessage = "Please Select Route.")]
    public int RouteAreaID { get; set; }
    public int VendorID { get; set; }
    [Range(1, int.MaxValue)]
    [Required(ErrorMessage = "Please Select Driver")]
    public int UserId { get; set; }
    public string CustomerRefListID { get; set; }

    [Range(1, int.MaxValue)]
    [Required(ErrorMessage = "Please select customer from auto fill option")]}

以下是Jquery代码。

$("#btnAddall").click(function () {
    var itemlist = new Array();
    var QtyCheck = true;
    var count = 0;
    $("#tblData tr:not(:first)").each(function () {
        var tds = $(this).find("td");
        //Getting Selected List Data.closest('tr')
        var SitemList;
        if ($(tds[3]).find("input").val() > 0) {
            SitemList = { ItemID: $(tds[0]).find("input").val(), Name: $(tds[1]).html(), Quantity: $(tds[3]).find("input").val() }
            itemlist.push(SitemList);
        }
        else {

            QtyCheck = false;
            return false;
        }
    });

        //GET: FormData
        var modal = $('#OrderList').serialize();
        //console.log(modal);

        var Itemdata = JSON.stringify(itemlist);
        var Alldata = { Items: itemlist, _Orders: modal };

        if (QtyCheck && itemlist.length > 0)
        {

            $.ajax({

                url: '@Url.Action("Unscheduleditem", "UscheduledDelivery")',
            dataType: "json",
            data: JSON.stringify(Alldata),
            type: "POST",
            contentType: "application/json; charset=utf-8",
            success: function (data) {

                if (data.error == 1) {
                    Alert(2, data.massage);
                }
                else {
                    Alert(1, data.massage);
                    //$("#UnscheduledDelivery").();
                    window.location.reload();
                }
            },
            error: function ()
            {
                Alert(2, 'Failed ! Please make sure all required field selected');
            }
        });
}
else
{
    Alert(2, '! Please Enter Valid Quantity');
}


    });

1 个答案:

答案 0 :(得分:2)

ModelState.IsValid在收到请求时引用请求中的对象。

通常情况下,它会在方法的顶部进行检查,因为当您决定是继续进行还是完全拒绝该请求时,会进行检查。

以后改变对象基本上不会影响任何事情。

话虽如此,您实际上可以使用以下内容手动触发模型验证:Manually invoking ModelState validation

最好的部分是,您可以为任何使用DataAdnotations标记属性的对象触发它,然后您可以检查该验证的结果是什么。