1

Everytime this form does a post back i get viewmodel as null in my controller. Could anyone please help me what am i missing here?

Here is my ViewModel

public class CarViewModel
{
    [Required(ErrorMessage = "Please enter the Reg No")]
    public string RegNo { get; set; }

    [Required(ErrorMessage = "Please enter Model")]
    public string CarModel { get; set; }

    [Required(ErrorMessage = "Please select one of the status")]
    public int? Status { get; set; }

    [Required(ErrorMessage = "Please enter colour")]
    public string Colour { get; set; }

    public List<SelectListItem> ModelList
    {
        get;
        set;
    }

    public List<SelectListItem> Statuses
    {
        get;
        set;           
    }
}

Here is my Controller

   [HttpGet]
    public ActionResult Create()
    {
        CarViewModel model = new CarViewModel();
        var statusList = _service.GetAllStatusList();
        var modelList = _service.GetAllModelList();
        model.Statuses = statusList.Select(x => new SelectListItem
        {
            Text = x.description,
            Value = x.id.ToString()
        }).ToList();

        model.ModelList = modelList.Select(x => new SelectListItem
        {
            Text = x.model_name,
            Value = x.model_id.ToString()
        }).ToList();

        return View(model);
    }

    //
    // POST: /CarRental/Create
    [HttpPost]
    [ValidateAntiForgeryToken]
    public ActionResult Create(CarViewModel model)
    {
        try
        {
            // TODO: Add insert logic here
            if (ModelState.IsValid)
            {
                car car = new car { colour = model.Colour, registration = model.RegNo, status = model.Status };
                _service.RegisterCar(car);
                return View(model);
            }
            else
            {
                return View(model);
            }
            //  return RedirectToAction("Index");
        }
        catch (Exception)
        {
            return View(model);
        }
    }

Here is my View

   @model CarRentalUI.Models.CarViewModel
   @{
     ViewBag.Title = "Create";
   }

   <h2>Create</h2>

   @using (Html.BeginForm("Create","CarRental",FormMethod.Post))
   {
       @Html.AntiForgeryToken()
       @Html.ValidationSummary(true)   
       @Html.LabelFor(x=>x.RegNo)
       @Html.TextBoxFor(x=>x.RegNo)         
       @Html.ValidationMessageFor(x=>x.RegNo)
       <br/>
      @Html.LabelFor(x=>x.CarModel)         
      @Html.DropDownListFor(x=>x.CarModel,Model.ModelList,"Please Make a Selection")
      @Html.ValidationMessageFor(x=>x.Model)

      <br/>
      @Html.LabelFor(x=>x.Status)         
      @Html.DropDownListFor(x=>x.Status, Model.Statuses,"Please Make a Selection")    
      @Html.ValidationMessageFor(x=>x.Status)

      <input type="submit" value="Submit" id="submitButton"/>
  }
Sike12
  • 1,232
  • 6
  • 28
  • 53
  • 1
    why you need hidden control here? – Jalpesh Vadgama Apr 15 '14 at 12:38
  • That was one of the solution mentioned in other articles so i tried my luck with it but still didn't work. – Sike12 Apr 15 '14 at 12:46
  • 1
    Try html.editorfor instead of html.textboxfor and then see – Jalpesh Vadgama Apr 15 '14 at 12:49
  • 2
    @Sike12 You don't need that hidden field. It's used when you need model binding but it seems that the problem here is different. The first thing that looks suspicious is the `Model` property which is valid keyword. Is it possible to change the property name from `Model` to `CarModel` or something like this and see if something changes? – Leron Apr 15 '14 at 12:50
  • Jalpesh Vadgama It doesn't make any different changing it as i was still getting null – Sike12 Apr 15 '14 at 12:55
  • Leron: Ur right i had to change Model to CarModel now the text box portion works but for the drop downs selection i am still getting null values in the controller – Sike12 Apr 15 '14 at 12:56
  • 1
    You need to remove the HiddenFor's – matthijsb Apr 15 '14 at 13:03
  • 1
    @Sike12 You are creating the `DropDownListFor` in a wrong way. See this question here for some guideness - http://stackoverflow.com/questions/19476530/html-dropdownlistfor-selected-value-not-being-set . Keep in mind that maybe `Status` can not be nullable. I'm not sure about that but make it work with `int` and then try to change it to `int?` – Leron Apr 15 '14 at 13:06
  • @Leron even the article you are pointing me to recommends my approach – Sike12 Apr 15 '14 at 13:13
  • 1
    What is sent to server ? ( look in your network tab of browser's developer tools ) – Cosmin Apr 15 '14 at 13:28
  • 1
    @Sike12 You are right, I guess there's something simple that causes the problem. `matthijsb` wrote that he made a working solution. Maybe just ask him for the `Html.DropDownListFor` code. What I would suggest is to change the `status` property to `string`. – Leron Apr 15 '14 at 13:37
  • @Kosmo Its the model object with the filled in values. – Sike12 Apr 15 '14 at 14:30
  • @Leron In the Database the status is a foreign key which links to the status list (Table) so it has to be int for now. Thanks for the advice though. – Sike12 Apr 15 '14 at 14:30

2 Answers2

1

Use

return RedirectToAction("Create");

Instead of

 return View(model);
D Mishra
  • 1,518
  • 1
  • 13
  • 17
1
  • Remove the HiddenFor's
  • Make sure the value of statuses are parseable int's
  • Add the Colour dropdown

I just created a test project according to your sample code and it seems to work ( https://i.stack.imgur.com/DaWzP.png )

matthijsb
  • 909
  • 5
  • 12