I have a view model
public class DeviceModelEntryViewModel
{
public int ID { get; set; }
[Required]
[MaxLength(255)]
public String Model { get; set; }
[MaxLength(255)]
public String Description { get; set; }
[Required]
[Display(Name = "Manufacturer")]
public int ManufacturerID { get; set; }
public SelectList ManufacturerList { get; set; }
}
In the DeviceModelController my Create method goes something like this:
[HttpPost]
public ActionResult Create(DeviceModelEntryViewModel model)
{
if (ModelState.IsValid)
{
...
return RedirectToAction("Edit", new { id });
}
return View(model);
}
The Create View is as follows:
@model ICMDB.ViewModels.DeviceModelEntryViewModel
@{ ViewBag.Title = "ICMD - Create Device Model"; }
<h2>Create Device Model</h2>
<div class="form-div">
@using (Html.BeginForm()) {
@Html.ValidationSummary(true)
<fieldset>
<div class="editor-label">
@Html.LabelFor(model => model.Model)
</div>
<div class="editor-field">
@Html.EditorFor(model => model.Model)
@Html.ValidationMessageFor(model => model.Model)
</div>
<div class="editor-label">
@Html.LabelFor(model => model.Description)
</div>
<div class="editor-field">
@Html.EditorFor(model => model.Description)
@Html.ValidationMessageFor(model => model.Description)
</div>
<div class="editor-label">
@Html.LabelFor(model => model.ManufacturerID)
</div>
<div class="editor-field">
@Html.DropDownListFor(model => model.ManufacturerID,
Model.ManufacturerList, "--None--")
@Html.ValidationMessageFor(model => model.ManufacturerID)
</div>
</fieldset>
<input type="submit" value="Save" class="form-button"/>
}
@using (Html.BeginForm("Index", "DeviceModel"))
{ <input type="submit" value="Cancel" class="form-button"/> }
</div>
For some reason, whenever this function (or the Edit function which has a similar declaration) is hit, model is null. I checked, and it doesn’t even hit the zero arg constructor for DeviceModelEntryViewModel. I have done this for all my other controllers with their appropriate view models and they all work fine. I can’t seem to see what the difference is with this one that stops it from working.
Any ideas?
Try changing the name of your Model property to something like:
public String ModelName { get; set; }Don’t forget to update your view as well. I believe that should get it working correctly as the word Model seems to act like a reserved word and confuses the model binder.
Edit: Here is a list of reserved words in Razor / MVC: Razor reseverd words