I'm trying to pass an object through a form to my controller with an AJAX call.
Here is the object, everything returns null/0 except AuctionId:
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; }
}
The Form:
<form id="createBid">
<div id="frmBid" class="form-inline">
<input name="Bidder" asp-for="@bidModel.Bidder" value="@User.Identity.Name" type="hidden" />
<input name="AuctionId" asp-for="@bidModel.AuctionId" value="@Model.AuctionId" type="hidden" id="auctionId" />
<label asp-for="@bidModel.Amount" />
<input name="Amount" asp-for="@bidModel.Amount" />
<button type="submit" id="submitBtn" class="btn btn-primary">Lägg</button>
</div>
</form>
Here is the AJAX call:
$('#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);
}
});
});
And then we have the action in the controller:
[HttpPost]
public async Task<IActionResult> 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);
}
So the problem is, that some value, not all values returns null.
Why isn't AuctionId null but the others are?
I also tried to make a new ViewModel, since I already had an Auction as Viewmodel in the view. I made a new with Auction and a Bid And i make the form look like this:
<form id="createBid">
<div id="frmBid" class="form-inline">
<input asp-for="BidVM.AuctionId" value="AuctionVM.AuctionId" type="hidden" id="auctionId" />
<label asp-for="BidVM.Amount" />
<input asp-for="BidVM.Amount" />
<button type="submit" id="submitBtn" class="btn btn-primary">Lägg</button>
</div>
</form>
But now everything is null
JsonPropertyin order to simplify the problem.