Simon Simon - 2 months ago 9
C# Question

C# MVC Post form not passing ID from view to controller

I am new to MVC. I work on an auction application. On the auction site, there should be a form for making a bid. I have a problem passing the auction parameter to the controller

My models:

public class Auctions
public int ID { get; set; }
public string title { get; set; }
(..) some other fields
public List<Bid> bids = new List<Bid>();

public class BiddingViewModel
public Auctions auctionToSend { get; set; }
public double bid { get; set; }

My view:

@model BiddingViewModel

@using(Html.BeginForm("CreateBid", "Auction", FormMethod.Post, new { enctype = "multipart/form-data" }))
@Html.EditorFor(model =>
<input type="submit" value="Make it work" />


and my controller:

public ActionResult AuctionPage(int id)
var tmp = _context.Auctions.FirstOrDefault(i => i.ID == id);

BiddingViewModel bvm = new BiddingViewModel
auctionToSend = tmp,
bid = -1

return View(bvm);

public async Task<ActionResult> CreateBid(BiddingViewModel bvm)
//After filling the form from view, the bvm.auctionToSend is null, whereas the value is visible
return RedirectToAction("AuctionList", "Auction");

My problem is that the auction data (perfectly visible in the view) is not sent back to the controller. I checked the internet and it showed me some naming-conflicts' solutions, so I made sure the naming is different, but this didn't fix my problem.


auctionToSend is a complex object and your use of @Html.HiddenFor(model=>model.auctionToSend) is generating

<input type="hidden" name="auctionToSend" value="yourAssembly.Auctions" ... />

If you just need the ID of the Auctions, then use

 @Html.HiddenFor(m => m.auctionToSend.ID)

otherwise you need to generate a hidden input for each property of Auctions but that would be inefficient, particularly as Auctions contains a property which is a collection, so if you need the Auctions object in the POST method, better to just get it again based on the ID value your submitting.

As a side note, you really should be using a view model with just properties for the double Bid and int AuctionID