I am trying to add a new object to a database in a controller action.
This is my model class.
public class Product
{
public int ProductID { get; set; }
[Required(ErrorMessage = "Please enter product name")]
public string Name { get; set; }
[Required(ErrorMessage = "Please enter product model")]
public string Model { get; set; }
[Required(ErrorMessage = "Please enter product serial")]
public string Serial { get; set; }
[Required(ErrorMessage = "Please choose dealer")]
public int DealerID { get; set; }
[Required]
public Guid ClientID { get; set; }
[Required(ErrorMessage = "Please choose employee")]
public Guid EmployeeID { get; set; }
public virtual Dealer Dealer { get; set; }
public virtual Client Client { get; set; }
public virtual Employee Employee { get; set; }
[DisplayName("Commercial use")]
public bool UseType { get; set; }
}
These are the steps to create a new product in the database.
public ViewResult Create()
{
PopulateDropDownLists();
var model = new Product();
return View(model);
}
[HttpPost]
public ActionResult Create(Product model)
{
try
{
if (ModelState.IsValid)
{
_repo.GetRepository<Product>().Add(model);
_repo.Save();
TempData["message"] = "Product was successfully created";
return RedirectToAction("List");
}
}
catch (DataException)
{
TempData["error"] =
"Unable to save changes. Try again, and if the problem persists, see your system administrator.";
return View("Error");
}
PopulateDropDownLists();
return View("Create");
}
CreateView has an appropriate model type (product type in this case). Code below
@using System.Web.Mvc.Html
@model STIHL.WebUI.Models.Product
@using (Html.BeginForm())
{
@Html.EditorFor(m => m.Name)
@Html.EditorFor(m => m.Model)
@Html.EditorFor(m => m.Serial)
<div class="form-group">
@Html.LabelFor(m => m.DealerID, "Dealer")
@Html.DropDownListFor(m => m.DealerID, new SelectList((IEnumerable)TempData["Dealers"],"DealerID", "DealerNumber"), string.Empty, new {@class = "form-control"})
@Html.ValidationMessageFor(m => m.DealerID, null, new {@class = "help-block"})
</div>
<div class="form-group">
@Html.LabelFor(m => m.EmployeeID, "Employee",new {@class = "control-label"})
@Html.DropDownListFor(m => m.EmployeeID, new SelectList((IEnumerable)TempData["Employees"],"EmployeeID", "FullName"),string.Empty, new {@class="form-control"})
@Html.ValidationMessageFor(m => m.EmployeeID, null, new {@class = "help-block"})
</div>
<div class ="ok-cancel-group">
<input class="btn btn-primary" type="submit" value="Create" />
@Html.ActionLink("Cancel", "List","Product",new {@class = "btn btn-primary"})
</div>
}
I always get a null reference instead of the model in action [HttpPost], but if I use ViewModel instead of Model, everything is fine (ViewModel code below)
public class ProductViewModel
{
public Product Product { get; set; }
}
I think this causes the model class to have virtual properties, but in any case, I don’t understand why this is normal when I use ViewModel. Can anyone answer me? thanks in advance.