0

I am inserting data in a database using ajax and jquery. when I click the save button then JSON function not Calling controller. I have also use debug and JSON data return this

{"Qt_ID":2,"EnteryDate":"11/10/2018","Purpose":"test","Quot":[{"Srno":"1","PartyName":"Brisk","file":"C:\\fakepath\\aaa.png","IsMature":"true"}],"AddNew":"New"}

but not passing to the controller. Anyone tell me where I am wrong and what is the problem in my code. i try a lot off but i don't understand what is the problem . any expert kindly review my code and tell me where i am wrong.

C#

 public ActionResult mQuotationInsert(int Qt_ID, string EnteryDate, string Purpose, Quotation[] Quot, string AddNew, HttpPostedFileBase file)
        {
            string result = "Error! Order Is Not Complete!";
            try
            {
                objQuotation.QuotationInsert(Qt_ID, EnteryDate, Purpose, Quot, AddNew, file);
                ModelState.Clear();
                result = "Quotation Inserted Successfully!";
                return Json(result, JsonRequestBehavior.AllowGet);
            }
            catch (Exception)
            {

                throw;
            }

        }



  public int QuotationInsert(int Qt_ID, string EnteryDate, string Purpose, Quotation[] Quot, string AddNew, HttpPostedFileBase file)
        {
            try
            {
                con.Open();
                tr = con.BeginTransaction();

                if (AddNew == "New")
                {

                    cmd = new SqlCommand("Select Right('00' + Cast(ISNULL(MAX(Qt_ID),0)+1  as varchar(2)) + '', 2) from QuotationMain", con);
                    cmd.Transaction = tr;
                    Qt_ID = Convert.ToInt32(cmd.ExecuteScalar().ToString());

                    cmd = new SqlCommand("Sp_QuotationMainInsert", con);
                }
                else
                    cmd = new SqlCommand("Sp_QuotationMainUpdate", con);

                cmd.Parameters.AddWithValue("@Qt_ID", Qt_ID);
                cmd.Parameters.AddWithValue("@Comp_ID", 1);

                if (EnteryDate != null)
                    cmd.Parameters.AddWithValue("@EnteryDate", EnteryDate);
                else
                    cmd.Parameters.AddWithValue("@EnteryDate", string.Empty);

                cmd.Parameters.AddWithValue("@Username", HttpContext.Current.Session["AgentName"]);
                cmd.Parameters.AddWithValue("@Purpose", Purpose);

                cmd.CommandType = CommandType.StoredProcedure;
                cmd.Transaction = tr;
                cmd.ExecuteNonQuery();



                if(Quot !=null)
                {
                    for (int i = 0; i < Quot.Length; i++)
                    {
                        try
                        {

                            string ImageName = System.IO.Path.GetFileName(file.FileName);
                            string physicalPath = HttpContext.Current.Server.MapPath("~/Images/" + ImageName);
                            file.SaveAs(physicalPath);


                            if (AddNew == "New")
                            {
                                cmd = new SqlCommand("Select ISNULL(MAX(Qt_Dt_ID), 0) + 1 from QuotationDetail", con);
                                cmd.Transaction = tr;
                                mQt_Det_ID = Convert.ToInt32(cmd.ExecuteScalar());


                                cmd = new SqlCommand("Sp_QuotationDetailInsert", con);
                                cmd.Parameters.AddWithValue("@Qt_Dt_ID", mQt_Det_ID);

                            }

                            else if (AddNew == "Edit")
                            {
                                cmd = new SqlCommand("Sp_QuotationDetailUpdate", con);
                                cmd.Parameters.AddWithValue("@Qt_Dt_ID", Quot[i].Qt_Dt_ID);
                            }

                            cmd.CommandType = CommandType.StoredProcedure;

                                cmd.Parameters.AddWithValue("@Qt_Dt_ID", mQt_Det_ID);
                                cmd.Parameters.AddWithValue("@Qt_ID", Qt_ID);
                                cmd.Parameters.AddWithValue("@SrNo", Quot[i].Srno);

                                cmd.Parameters.AddWithValue("@PartyName", Quot[i].PartyName);
                                cmd.Parameters.AddWithValue("@IsMature",Quot[i].IsMature);

                            if (file != null)
                                cmd.Parameters.AddWithValue("@Image", ImageName);

                            cmd.Transaction = tr;
                            cmd.ExecuteNonQuery();
                        }
                        catch (Exception)
                        {

                            throw;
                        }


                    }
                }



                tr.Commit();
                return i;
            }
            catch (SqlException sqlex)
            {
                tr.Rollback();
                throw sqlex;  // read all sql error 
            }
            catch (Exception ex)
            {
                tr.Rollback();
                throw ex; // General execption

            }
            finally
            {
                con.Close();
            }

jquery

function saveQuotation(data) {

            if ($.trim($("#Qt_ID").val()) == "" || $.trim($("#txtNEnteryDate").val()) == "" || $.trim($("#txtNPurpose").val()) == "") return;

            return $.ajax({
            contentType: 'application/json; charset=utf-8',
                dataType: 'json',
                type: 'POST',
                url: "/Home/mQuotationInsert",
                data: data,
                success: function (result) {
            alert(result);
        location.reload();
                },
                error: function () {
            alert("Error!")
        }
        });

        }

        //Collect Multiple Order List For Pass To Controller

        $("#saveQuotation").click(function (e)
        {
            e.preventDefault();
            var QuotationArr = [];
            QuotationArr.length = 0;

            $.each($("#detailsTable tbody tr"), function () {

                QuotationArr.push({
                Srno: $(this).find('td:eq(0)').html(),
                PartyName: $(this).find('td:eq(1)').html(),
                file: $(this).find('td:eq(2)').html(),
                IsMature: $(this).find('td:eq(3)').html()


            });
        });

            var data = JSON.stringify({
                Qt_ID: parseInt($("#Qt_ID").val()),
                EnteryDate: $("#txtNEnteryDate").val(),
                Purpose: $("#txtNPurpose").val(),
                Quot: QuotationArr,
                AddNew: $("#AddNew").val()
            });

            $.when(saveQuotation(data)).then(function (response) {
            console.log(response);
        }).fail(function (err) {
            console.log(err);
        });
    });

HTML

<div class="modal fade" id="centralModalLGInfoDemo" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true" data-backdrop="static" data-keyboard="false">
            <div class="modal-dialog modal-lg modal-notify modal-info" role="document">
                <!--Content-->

                <div class="modal-content" style="width:140%">
                    <!--Header-->
                    <div class="modal-header">
                        <p class="heading lead">Add New Quotation</p>
                        <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                            <span aria-hidden="true" class="white-text">&times;</span>
                        </button>
                    </div>
                    <!--Body-->
                    <form id="NewQuotationForm">
                        <div class="modal-body">
                            <div class="form-row">
                                <div class="col" id="Qt_ID">

                                    <div class="md-form">
                                        @Html.TextBox("Qt_ID", (string)ViewBag.QuotationMaxNo, new { @class = "form-control mr-sm-2 w-5", @id = "Qt_ID", @readonly=true, Required = true })
                                    </div>
                                </div>
                                <div class="col">

                                    <div class="md-form mr-4">
                                        @Html.TextBoxFor(m => m.EnteryDate, new { @class = "form-control", @id = "txtNEnteryDate", Required = true })

                                        <label for="lblEntryDate">Entry Date</label>
                                    </div>
                                </div>

                                <div class="col">

                                    <div class="md-form">

                                        @Html.TextBoxFor(m => m.Purpose, new { @class = "form-control", @id = "txtNPurpose", Required = true })

                                        <label for="lblPurpose">Purpose</label>
                                    </div>

                                </div>



                            </div>


                            <!--Detail-->
                            <h5 style="margin-top:10px;color:#ff6347">Quotation Details</h5>
                            <hr />
                            <div>
                                <div class="form-row">
                                    <div class="col">

                                        <div class="md-form">
                                            <label for="lblPartyName">Party Name</label>
                                            <input type="text" id="PartyName" name="PartyName" placeholder="Party Name" class="form-control" ,Required=true />


                                        </div>
                                    </div>
                                    <div class="col">

                                        <form class="md-form">
                                            <label for="lblPartyName">Image File</label>
                                            <div class="file-field">
                                                <div class="btn btn-outline-success  btn-sm float-left">

                                                    <input type="file" id="file" name="file">
                                                </div>
                                                <div class="file-path-wrapper" hidden>
                                                    <input class="file-path validate" type="text" placeholder="Upload your file">
                                                </div>
                                            </div>
                                        </form>
                                    </div>
                                    <div class="col">
                                        <!-- IsMature-->
                                        <div class="custom-control custom-checkbox custom-control-inline">
                                            @Html.CheckBoxFor(m => m.IsMature, new { @class = "custom-control-input", @id = "chkNIsMature" })

                                            <label class="custom-control-label" for="chkNIsMature">Mature</label>
                                        </div>
                                    </div>


                                    <div class="col-md-2 col-lg-offset-4">
                                        <a id="addToList" class="btn btn-primary">Add To List</a>
                                    </div>
                                </div>
                                <table id="detailsTable" class="table">
                                    <thead style="background-color:#007bff; color:white">
                                        <tr>
                                            <th style="width:2%">SrNo.</th>
                                            <th style="width:40%">Party Name</th>
                                            <th style="width:30%">Image</th>
                                            <th style="width:30%">Mature</th>
                                            <th style="width:10%"></th>
                                        </tr>
                                    </thead>
                                    <tbody></tbody>
                                </table>
                            </div>
                            <div class="modal-footer">
                                <button type="reset" class="btn btn-primary" data-dismiss="modal">Close</button>
                                <button id="saveQuotation" type="submit" class="btn btn-primary">Save Record</button>
                            </div>
                        </div>
                    </form>



                </div>

                <!--/.Content-->
            </div>
        </div>

2 Answers 2

2

First of all, create a model in server side

public class DataModel
{
    public int Qt_ID { get; set; }
    public string EnteryDate { get; set; }
    public string Purpose { get; set; }
    public Quotation[] Quot { get; set; }
    public string AddNew { get; set; }
}

public class Quotation
{
    public int Qt_Dt_ID { get; set; }
    public int Srno { get; set; }
    public string PartyName { get; set; }
    public bool IsMature { get; set; }
}

It's probably better to use some validations too.

Then instead of passing every property individually, use the DataModel class

using Microsoft.AspNetCore.Mvc;

[HttpPost]
public ActionResult mQuotationInsert([FromBody] DataModel model)
{
    // do the rest
}

Note the attributes [HttpPost] and [FromBody]. These two help the data bind correctly.

Uploaded File

You have two options.

  1. Handle the uploaded file manually
  2. Or create a model binder and put that responsibility on its shoulder

For number 2, take a look here

The rest of your code is fine.

Sign up to request clarification or add additional context in comments.

9 Comments

Frombody attributr could not be found . when i write in controller
It's FromBody with capital B
No still same problem.
ok. the problem is this : image: $(this).find('td:eq(2)').html(), is this correct syntax for image url.
When i remove this work fine otherwise show msg in alert error .
|
0

try using [HttpPost] attribute above controller method

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.