Click here to Skip to main content
15,499,289 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
C#
here is my controller code ...
<pre lang="C#">[HttpPost]
        public ActionResult Create(FormCollection collection,string command,List&lt;Orderdetail&gt; Values)
        {
            try
            {
                //if (ModelState.IsValid)
                //{ 
               
                            List&lt;FILEDETAIL&gt; FILEDETAILs = new List&lt;FILEDETAIL&gt;();
                            for (int i = 0; i &lt; Request.Files.Count; i++)
                            {
                                var file = Request.Files[i];
                                if (file != null &amp;&amp; file.ContentLength &gt; 0)
                                {
                                    var fileName = Path.GetFileName(file.FileName);
                                    FILEDETAIL fILEDETAIL = new FILEDETAIL()
                                    {
                                        FileName = fileName,
                                        Extension = Path.GetExtension(fileName),
                                        Id = Guid.NewGuid()
                                    };
                                    FILEDETAILs.Add(fILEDETAIL);

                                    var path = Path.Combine(Server.MapPath(&quot;~/App_Data/Upload&quot;), fILEDETAIL.Id + fILEDETAIL.Extension);
                                    file.SaveAs(path);
                                }                               
                            }

                            List&lt;REQ_ITEM_DETAILS&gt; reqitem = new List&lt;REQ_ITEM_DETAILS&gt;();
                            for (int i=0;i&lt;Values.Count;i++ )
                            {
                                REQ_ITEM_DETAILS req = new REQ_ITEM_DETAILS()
                                {
                                    CO_COMP_CODE=&quot;0&quot;,
                                    CO_REQ_ID=reqviewmodel.tBL_REQUISITION.CO_REQ_ID,
                                    DESCRIPTION=Values[i].itemName,
                                    QUANTITY=Values[i].quantity,
                                    RATE=Values[i].rate,
                                    TOTAL=Values[i].TotalAmount,
                                    UNIT_ID=Convert.ToInt32(Values[i].unit)
                                };
                                reqitem.Add(req);
                            }
                                reqviewmodel.Addrequisition(collection, FILEDETAILs, Request.Files.Count,reqitem);
                     
                        return RedirectToAction(&quot;Index&quot;);

                //}
                //return View();
               
            }
            catch(Exception ex)
            {
                return View();
            }
        }</pre>

on view i use this 
<pre lang="JavaScript">$(&#39;#submit&#39;).click(function () {
            //validation of order
            var isAllValid = true; 
            var params = $(&#39;#f11&#39;).serializeArray();
            ////Save if valid
            if (isAllValid) {
                var data = {
                   
                    &quot;command&quot;: &quot;Insert&quot;,
                    //OrderDate: $(&#39;#orderDate&#39;).val().trim(),
                    ////Sorry forgot to add Description Field
                    
                    //Description: $(&#39;#description&#39;).val().trim(),
                    &quot;Values&quot;: orderItems,
                    &quot;collection&quot;: params
                }
                //$(this).val(&#39;Please wait...&#39;);

                $.ajax({
                    url: &#39;/Requisition/Create&#39;,
                    type: &quot;POST&quot;,
                    data: JSON.stringify(data),
                    dataType: &quot;JSON&quot;,
                    contentType: &quot;application/json&quot;,                   
                    success: function (d) {
                        //check is successfully save to database
                        if (d.status == true) {
                            //will send status from server side
                            alert(&#39;Record Save has been  Successfully...&#39;);
                            //window.location.href = &#39;/Budget/BudgetList&#39;;
                            //clear form
                            //orderItems = [];
                            //$(&#39;#orderNo&#39;).val(&#39;&#39;);
                            //$(&#39;#orderDate&#39;).val(&#39;&#39;);
                            //$(&#39;#orderItems&#39;).empty();
                        }
                        else {
                            alert(&#39;Failed&#39;);
                        }
                        //$(&#39;#submit&#39;).val(&#39;Save&#39;);
                    },
                    error: function () {
                        alert(&#39;Error. Please try again.&#39;);
                        //$(&#39;#submit&#39;).val(&#39;Save&#39;);
                    }
                });</pre>


What I have tried:

here is my controller code ...
C#
[HttpPost]
        public ActionResult Create(FormCollection collection,string command,List<Orderdetail> Values)
        {
            try
            {
                //if (ModelState.IsValid)
                //{ 
               
                            List<FILEDETAIL> FILEDETAILs = new List<FILEDETAIL>();
                            for (int i = 0; i < Request.Files.Count; i++)
                            {
                                var file = Request.Files[i];
                                if (file != null && file.ContentLength > 0)
                                {
                                    var fileName = Path.GetFileName(file.FileName);
                                    FILEDETAIL fILEDETAIL = new FILEDETAIL()
                                    {
                                        FileName = fileName,
                                        Extension = Path.GetExtension(fileName),
                                        Id = Guid.NewGuid()
                                    };
                                    FILEDETAILs.Add(fILEDETAIL);

                                    var path = Path.Combine(Server.MapPath("~/App_Data/Upload"), fILEDETAIL.Id + fILEDETAIL.Extension);
                                    file.SaveAs(path);
                                }                               
                            }

                            List<REQ_ITEM_DETAILS> reqitem = new List<REQ_ITEM_DETAILS>();
                            for (int i=0;i<Values.Count;i++ )
                            {
                                REQ_ITEM_DETAILS req = new REQ_ITEM_DETAILS()
                                {
                                    CO_COMP_CODE="0",
                                    CO_REQ_ID=reqviewmodel.tBL_REQUISITION.CO_REQ_ID,
                                    DESCRIPTION=Values[i].itemName,
                                    QUANTITY=Values[i].quantity,
                                    RATE=Values[i].rate,
                                    TOTAL=Values[i].TotalAmount,
                                    UNIT_ID=Convert.ToInt32(Values[i].unit)
                                };
                                reqitem.Add(req);
                            }
                                reqviewmodel.Addrequisition(collection, FILEDETAILs, Request.Files.Count,reqitem);
                     
                        return RedirectToAction("Index");

                //}
                //return View();
               
            }
            catch(Exception ex)
            {
                return View();
            }
        }


on view i use this
JavaScript
$('#submit').click(function () {
            //validation of order
            var isAllValid = true; 
            var params = $('#f11').serializeArray();
            ////Save if valid
            if (isAllValid) {
                var data = {
                   
                    "command": "Insert",
                    //OrderDate: $('#orderDate').val().trim(),
                    ////Sorry forgot to add Description Field
                    
                    //Description: $('#description').val().trim(),
                    "Values": orderItems,
                    "collection": params
                }
                //$(this).val('Please wait...');

                $.ajax({
                    url: '/Requisition/Create',
                    type: "POST",
                    data: JSON.stringify(data),
                    dataType: "JSON",
                    contentType: "application/json",                   
                    success: function (d) {
                        //check is successfully save to database
                        if (d.status == true) {
                            //will send status from server side
                            alert('Record Save has been  Successfully...');
                            //window.location.href = '/Budget/BudgetList';
                            //clear form
                            //orderItems = [];
                            //$('#orderNo').val('');
                            //$('#orderDate').val('');
                            //$('#orderItems').empty();
                        }
                        else {
                            alert('Failed');
                        }
                        //$('#submit').val('Save');
                    },
                    error: function () {
                        alert('Error. Please try again.');
                        //$('#submit').val('Save');
                    }
                });
Posted
Updated 6-Apr-16 23:24pm
Comments
Richard Deeming 6-Apr-16 9:56am     CRLF
You seem to have forgotten to ask a question. What part of the code you've posted isn't working? What errors are you getting?

1 solution

Note that form collection is name-value pairs similar to json, but is NOT json.

You should use just serialized form string like this:
JavaScript
var form = $("#yourformid").serialize();
$.ajax({
    type: "POST"
    url: "/Requisition/Create",
    data: form,
    dataType: "json",
    success: function (data) {
        if (data.result == "Error") {
            alert(data.message);
        }
    }
});


Serializing the form should give you what you ask for.

But why are you even trying to get form collection when you're creating JSON data object?
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900