2011-05-31 72 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。

相關問題