如何在ASP.NET MVC中用 AJAX 实现JSON对象到视图模型类的Map

pvcm50d1  于 2022-12-24  发布在  .NET
关注(0)|答案(3)|浏览(145)

我在ASP .NETMVC中将JSON对象Map到类时遇到了问题。
我正在使用 AJAX 发送一个对象,控制器接收到null -请帮助我。
以下是我的看法:

@model List<Ahmed_Solution.Models.ViewModel>

@{
    Layout = null;
}

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

<div class="modal-footer">
    <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" class="btn btn-default" data-dismiss="modal" value="Cancel">
    <button id="Save-Greidge" class="btn bg-gradient-primary" onclick="SubmitArraytoController()">Save Data</button>
</div>

下面是我的模型类:

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

下面是控制器方法:

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

现附上截图以说明有关情况。
先谢了
You can see view model object is null here

byqmnocz

byqmnocz1#

尝试以下方法

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

3htmauhk2#

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

//在控制器中

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

}

wz3gfoph

wz3gfoph3#

更改json_对象

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

和行动

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

相关问题