0

I am trying to make model validation work when passing collection to new data objects example is given below in image.

enter image description here

Problem here lies is that it always shows true condition even if properties are given data annotations.e.g.:-

enter image description here

Here is the controller side code below.

[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" });
        }
    }

Here is the Business Layer side code given below.

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")]}

Here is the Jquery code below.

$("#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');
}


    });
Code Hard
  • 21
  • 3
  • [Do not post images of code or errors!](https://meta.stackoverflow.com/q/303812/995714) Images and screenshots can be a nice addition to a post, but please make sure the post is still clear and useful without them. If you post images of code or error messages make sure you also copy and paste or type the actual code/message into the post directly. – Rory McCrossan Apr 10 '18 at 10:00
  • @RoryMcCrossan ok – Code Hard Apr 10 '18 at 10:01
  • @RoryMcCrossan,@phuzi please check it is updated with Controller,Properties(data annotations),JQuery code. – Code Hard Apr 10 '18 at 10:09
  • 1
    `ModelState` relates to the data you have posted in the request (i.e it validates the properties of your `Items` collection). Creating a new object and setting invalid properties does not change `ModelState` –  Apr 10 '18 at 10:18
  • @StephenMuecke understood. – Code Hard Apr 10 '18 at 10:21

1 Answers1

2

ModelState.IsValid refers to the objects in your request, at the time the request is received.

Typically, it is checked right at the top of the method because that's when you decide if you want to proceed or simply reject the request altogether.

Changing the objects later won't affect anything basically.

This being said, you can actually manually trigger the model validation using something like this: Manually invoking ModelState validation

The best part is that you can trigger it for any object where properties are marked with DataAdnotations and you can then check to see what the result of that validation is.

Andrei Dragotoniu
  • 6,155
  • 3
  • 18
  • 32
  • It worked still i want to display error message as it is passing through Jquery rather than form post. Any help would be appreciated. – Code Hard Apr 10 '18 at 11:24