Home > Software design >  How to map JSON object to view model class in ASP.NET MVC using Ajax
How to map JSON object to view model class in ASP.NET MVC using Ajax

Time:12-24

I have problems mapping a JSON object to a class in ASP.NET MVC.

I am sending an object using Ajax and controller receives null - please help me.

Here is my view:

@model List<Ahmed_Solution.Models.ViewModel>

@{
    Layout = null;
}

<!DOCTYPE html>
@{
    Layout = null;
}

<div >
    <script>
        class Client {
            constructor(ntn, strn, first_name, last_name, address, phone, score) {
                this.NTN = ntn;
                this.STRN = strn;
                this.First_Name = first_name;
                this.Last_Name = last_name;
                this.Address = address;
                this.Phone = phone;
                this.Score = score;
            }
        }

        class Greidge
        {
            constructor(greidge_number, width,greidge_date,weaving_unit,gsm,quality,construction,quantity,unit,rolls)
            {
                this.greidge_number = greidge_number;
                this.greidge_Date = greidge_date;
                this.width = width;
                this.weaving_unit = weaving_unit;
                this.gsm = gsm;
                this.quality = quality;
                this.construction = construction;
                this.quantity = quantity;
                this.unit = unit;
                this.rolls_count = rolls;
            }
        }

        class Greidge_Client {
            constructor(gr, glist, lastgrnum, cl, clist, cnamelist, gquality, gqlist) {
                this.gr = gr;
                this.glist = glist;
                this.lastgrnum = lastgrnum;
                this.cl = cl;
                this.clist = clist;
                this.cnamelist = cnamelist;
                this.gquality = gquality;
                this.gqlist = gqlist;
            }
        }

        class Greidge_Quality {
            constructor(gquality) {
                this.gquality = gquality;
            }
        }
                                           
        function SubmitArraytoController()
        {
            var gr_number = $('#greidge_number').val();
            var gr_Date = document.getElementById("greidge_date").value;
            var party_ntn = $('#party_ntn').find(":selected").val()
            var party_name = $('#party_ntn').find(":selected").text();
            var gr_quality = $('#greidge_quality').find(":selected").val();
            var greidge_width = $('#greidge-width').val();
            var greidge_construction = $('#greidge-construction').val();
            var greidge_weaving_unit = $('#greidge-weaving-unit').val();
            var greidge_gsm = $('#greidge-gsm').val();
            var greidge_quantity = $('#greidge-quantity').val();
            var greidge_rolls = $('#greidge-rolls').val();
            var greidge_unit = $('#greidge-unit').find(":selected").val();

            var gr1 = new Greidge(gr_number, gr_Date, greidge_width, greidge_weaving_unit, greidge_gsm, gr_quality, greidge_construction, greidge_quantity, greidge_unit, greidge_rolls);
            var cl1 = new Client(party_ntn, "", party_name, "", "", "", "", "");
            var gql = new Greidge_Quality(gr_quality);

            var json_object = { 'viewmodel': new Greidge_Client(gr1, [], gr_number, cl1, [], [], gql, []) }
            //debugger;
            console.log(json_object)
            console.log(JSON.stringify(json_object));

            $.ajax({
                    contentType: 'application/json; charset=uf-8',
                    type: "POST",
                    url: "@Url.Action("SubmitGreidgeDetails", "Greidge")",
                    datatype: 'json',
                    data: JSON.stringify(json_object),
                    traditional: true
            });
        }
    </script>

    <input type="button"  data-dismiss="modal" value="Cancel">
    <button id="Save-Greidge"  onclick="SubmitArraytoController()">Save Data</button>
</div>

Here is my model class:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Data.SqlClient;
using System.Data;

namespace Ahmed_Solution.Models
{
    public class ViewModel
    {
        string constr = @"Data Source=hb.cvx9jeq87dws.ap-northeast-1.rds.amazonaws.com,1433;Initial Catalog=Hassan;User ID=Hammad;Password="12345";
        public Greidge gr = new Greidge();
        public List<Greidge> glist = new List<Greidge>();
        public Double lastgrnum;
        public Client cl = new Client();
        public List<Client> clist = new List<Client>();
        public List<Client> cnamelist = new List<Client>();
        public Greidge_Qualities gqlty = new Greidge_Qualities();
        // Fabric_Recieving fr = new Fabric_Recieving();
        public List<Greidge_Qualities> gqlist = new List<Greidge_Qualities>();

        public List<ViewModel> GetGreidgeDetails()
        {
            SqlConnection con = new SqlConnection(constr);
            List<ViewModel> vlist = new List<ViewModel>();
            
            SqlCommand com = new SqlCommand("GetAllGriedgeDetails", con);
            com.CommandType = CommandType.StoredProcedure;
            SqlDataAdapter da = new SqlDataAdapter(com);
            DataTable dt = new DataTable();
            con.Open();
            da.Fill(dt);
            con.Close();
            ViewModel vm = new ViewModel();

            vm.cnamelist = cl.GetAllClientNames();
            vm.gqlist = gqlty.GetAllQualityNames();
            vm.lastgrnum = gr.GetLastGreidgeNumber();

            // Bind EmpModel generic list using dataRow     
            foreach (DataRow dr in dt.Rows)
            {
                vm.cl.First_Name = dr["First_Name"].ToString();
                vm.cl.Last_Name = dr["Last_Name"].ToString();
                vm.gr.greidge_Date = Convert.ToDateTime(dr["Griedge_Date"].ToString());
                vm.gr.greidge_number = dr["Greidge_Number"].ToString();
                vm.gr.width = Convert.ToInt32(dr["Greidge_Width"].ToString());
                vm.gr.quality = dr["Quality"].ToString();
                vm.gr.construction = dr["Construction"].ToString();
                vm.gr.weaving_unit = dr["Weaving_Unit"].ToString();
                vm.gr.gsm = Convert.ToInt32(dr["GSM"].ToString());
                vm.gr.quantity = Convert.ToInt32(dr["Quantity"].ToString());
                vm.gr.unit = dr["Unit"].ToString();
                
                vlist.Add(vm);
            }

            if (vlist.Count == 0)
            {
                vlist.Add(vm);
            }

            return vlist;
        }
    }
}

Here is the controller method:

[HttpPost]
public ActionResult SubmitGreidgeDetails(ViewModel viewmodel)
{
    string name = viewmodel.gr.greidge_number;
    return View("GreidgeDetails", viewmodel.GetGreidgeDetails());
}

Screenshot is attached to illustrate the situation.

Thanks in advance

You can see view model object is null here

CodePudding user response:

Try the below

[HttpPost]
    public ActionResult SubmitGreidgeDetails([FromBody]ViewModel viewmodel)
        {
            string name = viewmodel.gr.greidge_number;
            return View("GreidgeDetails", viewmodel.GetGreidgeDetails());
        }

CodePudding user response:

  //I used below code to post form data, worked properly.          

                   $.ajax({
                     url: '/Batch/UpdateBatch',
                     type: "Post",
                     data: JSON.stringify(model),
                     dataType: "json",
                     contentType: "application/json"

                 }).done(function (response) {
                     if (response.success === true) {
                        //do stuff after success
                     }
                     else {
                     }
                 }).fail(function (response) {
                     //do stuff after failed
                 });

//In controller

[HttpPost]
public virtual async Task<JsonResult> SaveBatch(BatchViewModel model)
{
try
{
    var batch = await _batchService.CreateBatch(model);


    if (batch.Result)
    {
        return Json(new { success = batch.Result, message = batch.Message }, JsonRequestBehavior.AllowGet);
    }
    else
    {
        return Json(new { success = batch.Result, message = batch.Message }, JsonRequestBehavior.AllowGet);
    }
}
catch (Exception ex)
{
    return Json(new { success = false, message = ex.Message }, JsonRequestBehavior.AllowGet);
}

}

CodePudding user response:

change json_object

 var json_object =  new Greidge_Client(gr1, [], gr_number, cl1, [], [], gql, []) ;

and action

    [HttpPost]
    public ActionResult SubmitGreidgeDetails([FromBody]ViewModel viewmodel)
  • Related