开发者

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<SelectListIt开发者_JAVA百科em> 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?


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.


The controller method should have a property named model

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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜