有些值是null AJAX调用控制器ASP.Net Core

我正在尝试通过AJAX调用将对象通过表单传递给我的控制器。

这是对象,除AuctionId外,一切都返回null / 0

 public class BidModel { [JsonProperty("BudID")] public string BidId { get; set; } [JsonProperty("Summa")] public int Amount { get; set; } [JsonProperty("AuktionID")] public string AuctionId { get; set; } [JsonProperty("Budgivare")] public string Bidder { get; set; } } 

表格:

 

这是AJAX调用:

 $('#createBid').on('submit', function (e) { e.preventDefault(); var $form = $(this); $.ajax({ url: '@Url.Action("AddBid")', type: 'POST', dataType: 'html', data: JSON.stringify($form.serialize()), success: function (html) { $('#frmBid').html(html); } }); }); 

然后我们在控制器中执行操作:

 [HttpPost] public async Task AddBid(BidModel Bid) { var result = await _bidBusinessInterface.CreateBidAsync(Bid, Bid.AuctionId); if (result) { ViewBag.Message = "Bud lagt!"; } else { ViewBag.Message = "Bud förlågt!"; } return RedirectToAction("ViewDetails", Bid.AuctionId); } 

所以问题是,某些值,而不是所有值都返回null

为什么AuctionId不为null但其他是?

我还尝试制作一个新的ViewModel,因为我已经在视图中将View作为Viewmodel。 我用拍卖和出价创造了一个新的,我把表格看起来像这样:

 

但现在一切都是空的

一些代码清理后,这工作正常。

客户端 – ViewJS

 @model MyNamespace.BidModel @{ // Assuming you need to use local variable rather than just @model of BidModel type // If you can just use model - you will be able to bind imputs like this: //  // or //  // or (even better) // just use the tag helper asp-for like this: //  var bidModel = Model; } 

服务器端 – ControllerModel

 using System.Threading.Tasks; using Microsoft.AspNetCore.Mvc; using Newtonsoft.Json; namespace MyNamespace { public class BidModel { [JsonProperty("BudID")] public string BidId { get; set; } [JsonProperty("Summa")] public int Amount { get; set; } [JsonProperty("AuktionID")] public string AuctionId { get; set; } [JsonProperty("Budgivare")] public string Bidder { get; set; } } public class BidController : Controller { [HttpGet] public async Task AddBid() { // For demo purposes - pre-fill some values var model = new BidModel { Bidder = User.Identity.Name, Amount = 123, AuctionId = "A-ID", BidId = "B-ID" }; return View(model); } [HttpPost] public async Task AddBid(BidModel Bid) { // save new bid // return RedirectToAction("ViewDetails", Bid.AuctionId); return View(Bid); } } }