0

below is my code when I pass the data to the controller all the data is passing correctly but array is passed empty. please help. here is my model class and in model, I have the detail class list to access the detail record. in MVC here javascript if all valid it passes to the controller and here code produces error please help as soon as possible

model code is public class ClsFoodItem { public int ItemSysSeq { get; set; }

    [Display(Name = "Item Code")]
    //[StringLength(30, ErrorMessage = "The {0} must be at least {2} characters long.", MinimumLength = 3)]
    public string ItemCode { get; set; }


    [Display(Name = "Item Name")]
    //[StringLength(30, ErrorMessage = "The {0} must be at least {2} characters long.", MinimumLength = 5)]
    public string ItemName { get; set; }

     [Display(Name = "Description")]
    //[StringLength(50, ErrorMessage = "The {0} must be at least {2} characters long.", MinimumLength = 5)]
    public string ItemDescr { get; set; }


    //[StringLength(15, ErrorMessage = "The {0} must be at least {2} characters long.", MinimumLength = 11)]
    public string PurchaseUnit { get; set; }


    //[StringLength(15, ErrorMessage = "The {0} must be at least {2} characters long.", MinimumLength = 8)]
    public int UnitPrice { get; set; }

    //[StringLength(15, ErrorMessage = "The {0} must be at least {2} characters long.", MinimumLength = 8)]
    public int BoxPrice { get; set; }

    //[StringLength(15, ErrorMessage = "The {0} must be at least {2} characters long.", MinimumLength = 11)]
    public int UnitQtyinBox { get; set; }

    public string   ItemPicture { get; set; }

     public string Remarks { get; set; }

  public List<clsFoodItemsInStock> ItemInStock { get; set; }

}

//javascript code

if (isAllValid) {

                var data = {
                    ItemCode :   $('#ItemCode').val().trim(),
                    itemname:   $('#ItemName').val().trim(),
                    ItemDescr: $('#Itemdesp').val().trim(),
                    purchaseUnit: $('#purchaseUnit').val().trim(),
                    UnitPrice:  $('#UnitPrice').val().trim(),
                    unitQtyInBox:  $('#unitQtyInBox').val().trim(),
                    boxprice: $('#boxprice').val().trim(),
                    remarks: $('#remarks').val().trim(),
                    //mageData: $('#File1').val().trim(),
                     ItemInStock: stockvalues
                }
                    $(this).val('Please wait...');


                    $.ajax({

                        type: "POST",


                    url: '/FoodItem/Create/',



                   data: JSON.stringify(data),

                    dataType: 'JSON',

                    contentType: "application/json",

                    success: function (data) {
                        alert("array: " + stockvalues.join(', '));
                        //check is successfully save to database

                        if (data.status == true) {

                            //will send status from server side

                            alert('Successfully done.');

                            //clear form

                            stockvalues = [];

                            $('#ItemCode,#ItemName,#Itemdesp,#purchaseUnit,#UnitPrice,#unitQtyInBox,#boxprice,#remarks,#File1').val('');

                            $('#stockdetailitems').empty();

                        }

                        else {

                            alert('Error');

                        }


                        $('#submit').text('Save');
                    },

//controller code

re path in database

            //}
            using (SqlConnection sqlCon = new SqlConnection(obj_conn.Conn()))
            {

                sqlCon.Open();
                string query = "INSERT INTO [dbo].[FoodItem] (ItemCode,ItemName,ItemDescr,PurchaseUnit,UnitPrice,BoxPrice,UnitQtyinBox,ItemPicture,Remarks) ";
                query = query + "OUTPUT inserted .itemSysSeq Values(@ItemCode,@ItemName,@ItemDescr,@PurchaseUnit,@UnitPrice,@BoxPrice,@UnitQtyinBox,@ItemPicture,@Remarks)";
                SqlCommand sqlCmd = new SqlCommand(query, sqlCon);
                sqlCmd.Parameters.AddWithValue("@ItemCode", clsitem.ItemCode);
                sqlCmd.Parameters.AddWithValue("@ItemName", clsitem.ItemName);
                sqlCmd.Parameters.AddWithValue("@ItemDescr", (object)clsitem.ItemDescr ?? DBNull.Value);
                sqlCmd.Parameters.AddWithValue("@PurchaseUnit", (object)clsitem.PurchaseUnit ?? DBNull.Value);
                sqlCmd.Parameters.AddWithValue("@UnitPrice", (object)clsitem.UnitPrice ?? DBNull.Value);
                sqlCmd.Parameters.AddWithValue("@BoxPrice", (object)clsitem.BoxPrice ?? DBNull.Value);
                sqlCmd.Parameters.AddWithValue("@UnitQtyinBox", (object)clsitem.UnitQtyinBox ?? DBNull.Value);
                sqlCmd.Parameters.AddWithValue("@ItemPicture", (object)clsitem.ItemPicture ?? DBNull.Value);
                sqlCmd.Parameters.AddWithValue("@Remarks", (object)clsitem.Remarks ?? DBNull.Value);

                clsitem.ItemSysSeq = (int)sqlCmd.ExecuteScalar();

                foreach (var i in clsitem.ItemInStock)
                {

                    string query1 = "INSERT INTO [dbo].[FoodItemInStock] (ItemSysSeq,StockSysSeq,OpeningBalance,QtyInHand) ";
                    query1 = query1 + "Values(@ItemSysSeq,@StockSysSeq,@OpeningBalance,@QtyInHand)";
                    SqlCommand sqlCmd1 = new SqlCommand(query1, sqlCon);
                    sqlCmd1.Parameters.AddWithValue("@ItemSysSeq", clsitem.ItemSysSeq);
                    sqlCmd1.Parameters.AddWithValue("@StockSysSeq", 1);
                    sqlCmd1.Parameters.AddWithValue("@OpeningBalance", 200);
                    sqlCmd1.Parameters.AddWithValue("@QtyInHand", 55);

                    sqlCmd1.ExecuteNonQuery();
                }



                status = true;

            }

        }

        else
        {

            status = false;


        }

        return new JsonResult { Data = new { status = status } };
    }
Vikrant
  • 4,920
  • 17
  • 48
  • 72
Smart Pro
  • 3
  • 4
  • What list you're passing in javascript list ```stockvalues``` you need to pass same model properties in ```stockvalues``` list. – awais Sep 17 '19 at 18:15
  • yes im passing same model property to controller i.e ItemInStock: stockvalues .ItemInStock is model property that i passed – Smart Pro Sep 17 '19 at 18:19

1 Answers1

-1

https://dotnetfiddle.net/EukRIN

Here is your view

@{
    Layout = null;
}

<!DOCTYPE html>

<html>
<head>
    <meta name="viewport" content="width=device-width" />
    <title>Index5</title>
    <script src="~/Scripts/jquery-3.3.1.min.js"></script>
    <script>
        $(function () {
            $("#theButton").click(function () {
                var stockValues = $(".stockvalue");
                //https://stackoverflow.com/questions/5489461/pass-array-to-mvc-action-via-ajax
                var theArray = [];
                $.each(stockValues, function (index, aValue) {
                    theArray.push(aValue.value);
                })
                $.ajax({
                    type: "POST",
                    url: '/Home/MyAjaxCallMethodPassingArray/',
                    traditional: true,
                    data: { 'arrayOfValues': theArray }
                });
            })
        })
    </script>
</head>
<body>
    <div>
        <input type="text" class="stockvalue" />
        <input type="text" class="stockvalue" />
        <input type="text" class="stockvalue" />
        <input type="text" class="stockvalue" />
        <input type="button" value="Go" id="theButton" />
    </div>
</body>
</html>

Here is your action

    public string MyAjaxCallMethodPassingArray(String[] arrayOfValues)
    {
        //put a breakpoint here to see the arrayOfValues
        return "done";
    }
kblau
  • 2,094
  • 1
  • 8
  • 20
  • [HttpPost] public JsonResult Create(ClsFoodItem clsitem) { bool status = false; var isvalidModel = TryUpdateModel(clsitem); if (ModelState.IsValid) {//some code here } return new JsonResult { Data = new { status = status } }; } above iis my json call.so how i use this via this json call and how sent other data – Smart Pro Sep 17 '19 at 18:57
  • thanks for your response but its not working with jsonResult – Smart Pro Sep 17 '19 at 19:12
  • I can return ActionResult in my ajax method and do this: return new JsonResult { Data = new { status = "mystatus" } }; I also added dataType: "text" to my ajax call. – kblau Sep 17 '19 at 19:22
  • Can you provide more of an explanation to what you have done with this suggested answer? – CaptainGenesisX May 26 '22 at 19:37