ImmortalStrawberry
ImmortalStrawberry

Reputation: 6091

ViewModel has no properties set in Model using HttpPost Create method

I have a simple MVC3 app with an EF4 Model

Log
.Name
.CreatedDate
.LogTypeId

LogTypes
.Id
.Description

and a ViewModel

LogViewModel
Log MyLog
List<SelectListItem> Options

LogViewModel(){
  Log = new Log();
}

This displays in my view correctly and I can edit/update the values, display the drop down list and set the name to "MyTestValue".

However, in my controller's HttpPost Create method the properties for logVm.Log are not set?

[HttpPost]
public ActionResult Create(LogViewModel logVm){
  logVm.Log.Name == "MyTestvalue"; //false - in fact its null
}

What am I doing wrong?

Upvotes: 0

Views: 1348

Answers (2)

ImmortalStrawberry
ImmortalStrawberry

Reputation: 6091

The controller method should have a property named model

[HttpPost]
public ActionResult Create(LogViewModel **model**){
  **model**.Log.Name == "MyTestvalue"; //true    }

Upvotes: 0

Darin Dimitrov
Darin Dimitrov

Reputation: 1038710

That's probably because in your edit form you don't have corresponding values. So if yuor view is strongly typed to LogViewModel the form input names must be appropriately named:

@model LogViewModel
@using (Html.BeginForm())
{
    <div>
        @Html.LabelFor(x => x.Log.Name)
        @Html.EditorFor(x => x.Log.Name)
    </div>

    <div>
        @Html.LabelFor(x => x.Log.SomeOtherProperty)
        @Html.EditorFor(x => x.Log.SomeOtherProperty)
    </div>

    ...

    <input type="submit" value="OK" />
}

sop that when the form is submitted the POSTed values look like this:

Log.Name=foo&Log.SomeOtherProperty=bar

Now the default model binder will be able to successfully bind your view model. Also make sure that the properties you are trying to assign are public and that have a setter.

Upvotes: 3

Related Questions