2011-05-31 73 views
0

我有一个简单的MVC3应用程序,带有EF4型号ViewModel在Model中没有使用HttpPost Create方法设置属性

Log 
.Name 
.CreatedDate 
.LogTypeId 

LogTypes 
.Id 
.Description 

和ViewModel

LogViewModel 
Log MyLog 
List<SelectListItem> Options 

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

这在我的视图中正确显示,我可以编辑/更新值,显示下拉列表并设置名称为“MyTestValue”。

但是,在我的控制器的HttpPost Create方法中,没有设置logVm.Log的属性?

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

我做错了什么?

+0

您验证是否它logVm或logVm.Log是空? – 2011-05-31 14:54:28

+0

logVm.Log为空,logVm设置正确(我添加了一个字符串属性,这仍然在控制器中设置) – BlueChippy 2011-05-31 14:57:37

+0

YOU MUPPET!真的很简单...控制器方法中的属性需要被称为“模型”...当你想到它时显而易见! – BlueChippy 2011-05-31 14:58:29

回答

0

控制器方法应该有一个属性命名模式

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

这可能是因为在编辑表单中没有相应的值。因此,如果上你的看法是强类型到LogViewModel表单输入姓名必须适当命名为:

@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,当表单提交张贴的值是这样的:

Log.Name=foo&Log.SomeOtherProperty=bar 

现在的默认模型活页夹将能够成功绑定您的视图模型。还要确保你试图分配的属性是公共的,并且有一个setter。

相关问题