Code Hard
Code Hard

Reputation: 21

Model State Valid MVC Controller

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');
}


    });

Upvotes: 0

Views: 367

Answers (1)

Andrei Dragotoniu
Andrei Dragotoniu

Reputation: 6335

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.

Upvotes: 2

Related Questions