Sometimes it is the obvious things that trip us up the most. I had this class to be used in an ASP.NET MVC 3 Razor project.
public class SpecialOffer { public int ID { get; set; } [Required(ErrorMessage = "Offer Description is required")] public string Offer { get; set; } }
And in my controller the folowing
public ActionResult OfferCreate() { return View(new SpecialOffer()); } [HttpPost] public ActionResult OfferCreate(SpecialOffer Offer) { if (ModelState.IsValid) { try { _repository.InsertOffer(Offer); return RedirectToAction("OfferIndex"); } catch (Exception ex) { //error msg for failed insert in XML file ModelState.AddModelError("", "Error creating record. " + ex.Message); } } return View(Offer); }
So, why did my SpecialOffer offer object always return from my razor view as a null object? Simple because the object and one of its properties share the same name – Offer.Offer. This confuses the automatic binding used by MVC.
In the end I did not like the property name anyway. SpecialOffer.Offer did not read well so it became SpecialOffer.Description. And that fixes the problem with the automatic binding. I could also have just returned the model object as myOffer or model and still corrected the problem.
Simple, basic stuff. But annoying when things like that happen.
The post Why your MVC 3 Razor model object might be empty on post appeared first on Quickstep IT.