4

I try to add new entity in database in 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; }
}

This is actions for creating new product in 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 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 null reference instead model in [HttpPost] action, but if i use ViewModel instead Model everything is ok (ViewModel code below)

public class ProductViewModel
{
    public Product Product { get; set; }
}

I think it cause model class has virtual properties, but anyway i don't understand why it's ok when i use ViewModel. Can anyone answer me? Thx in advance.

4
  • 2
    I think u should put the view also!! Commented Dec 2, 2013 at 13:32
  • So what happens if you remove the "virtual" from the properties? Commented Dec 2, 2013 at 13:35
  • If i remove virtual property, i can use model class and it's ok without ViewModel Commented Dec 2, 2013 at 13:49
  • Question was edited. I put View code there Commented Dec 2, 2013 at 13:55

1 Answer 1

2

The virtual properties won't change the outcome. The issue is that the view is written to bind to the view model, therefore accepting the model isn't going to work. If you want to use the model; then bind the view to the model.

Sign up to request clarification or add additional context in comments.

1 Comment

When I use model class ViewCreate has appropriate type (Product). When I use ViewModel ViewCreate has ProductViewModel type.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.