ASP.NET MVC中Ajax传JSON到ViewModel类接收为null的求助
ASP.NET MVC中JSON到ViewModel映射失败:控制器接收ViewModel为null的解决方法
问题描述
在ASP.NET MVC项目中,通过Ajax发送JSON对象到控制器时,控制器接收的ViewModel始终为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, []) } 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(); 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(); 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()); }
核心问题与解决方案
1. ViewModel使用字段而非属性(致命问题)
ASP.NET MVC模型绑定仅识别带get/set的属性,不识别普通字段。需要将ViewModel中的所有字段改为属性:
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 { get; set; } = new Greidge(); public List<Greidge> glist { get; set; } = new List<Greidge>(); public double lastgrnum { get; set; } public Client cl { get; set; } = new Client(); public List<Client> clist { get; set; } = new List<Client>(); public List<Client> cnamelist { get; set; } = new List<Client>(); public Greidge_Qualities gqlty { get; set; } = new Greidge_Qualities(); public List<Greidge_Qualities> gqlist { get; set; } = new List<Greidge_Qualities>(); // GetGreidgeDetails方法保持不变 }
2. JSON字段名与ViewModel属性名不匹配
- 前端
Greidge_Client类中的gquality字段,对应ViewModel中的gqlty,需修改前端字段名:
class Greidge_Client { constructor(gr, glist, lastgrnum, cl, clist, cnamelist, gqlty, gqlist) { this.gr = gr; this.glist = glist; this.lastgrnum = lastgrnum; this.cl = cl; this.clist = clist; this.cnamelist = cnamelist; this.gqlty = gqlty; // 改为和ViewModel一致的名称 this.gqlist = gqlist; } }
3. 数据类型不匹配
- 前端
lastgrnum是字符串类型(输入框值),ViewModel中为double,需转成数字:
var json_object = { 'viewmodel': new Greidge_Client(gr1, [], parseFloat(gr_number), cl1, [], [], gql, []) }
4. Ajax请求参数错误
- 修正
contentType的编码拼写:uf-8改为utf-8 - 修正
datatype大小写为dataType(jQuery对参数大小写敏感) - 移除
traditional: true(仅用于传统数组序列化,JSON.stringify无需此配置)
$.ajax({ contentType: 'application/json; charset=utf-8', type: "POST", url: "@Url.Action("SubmitGreidgeDetails", "Greidge")", dataType: 'json', data: JSON.stringify(json_object), success: function(res) { console.log("提交成功"); }, error: function(xhr, err) { console.error("提交失败:", err); } });
5. Greidge构造函数参数顺序错误
前端实例化Greidge时的参数顺序和构造函数定义不匹配,导致字段赋值错位,修正构造函数参数顺序:
class Greidge { constructor(greidge_number, greidge_date, width, 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; } }
内容的提问来源于stack exchange,提问作者malik hammad
相关产品推荐
相关产品推荐

