2012-01-12 73 views
0

我嘗試在我的視圖中使用下拉列表來顯示作者列表(用戶)。我可以填充此下拉菜單並查看我的視圖中的內容。提交我的表單時,我在我的控制器中調試我的操作,並在檢查模型時,與我的下拉列表關聯的字段值爲空。我的表單提交時沒有任何值的下拉列表

這是我的動作控制器(表示我的視圖前):

public ActionResult Create() 
    { 
     IEnumerable<User> authors = m_AccountBusiness.GetAllUsers(); 

     PageCreateViewModel viewModel = new PageCreateViewModel 
     { 
      PageToCreate = new PageFullViewModel(), 
      Authors = authors.Select(x => new SelectListItem { Text = x.UserName, Value = x.UserID.ToString() }) 
     }; 

     return View(viewModel); 
    } 

這裏是(一部分)我的視圖:

@model MyBlog.ViewModels.PageCreateViewModel 

<h3>Create</h3> 

@using (Html.BeginForm()) 
{ 

@Html.ValidationSummary(true) 
@Html.HiddenFor(model => model.PageToCreate.PageID) 

<div class="editor-label"> 
    @Html.LabelFor(model => model.PageToCreate.Title) 
</div> 
<div class="editor-field"> 
    @Html.TextBoxFor(model => model.PageToCreate.Title, new { @class = "titleValue" }) 
    @Html.ValidationMessageFor(model => model.PageToCreate.Title) 
</div> 

<div class="editor-label"> 
    @Html.LabelFor(model => model.PageToCreate.Author) 
</div> 
<div class="editor-field">  
    @Html.DropDownListFor(model => model.PageToCreate.Author, Model.Authors, "Please select...")  
</div> 

這是我的PageCreateViewModel:

public class PageCreateViewModel 
{ 
    public PageFullViewModel PageToCreate { get; set; } 
    public IEnumerable<SelectListItem> Authors { get; set; } 
} 

有什麼想法?

謝謝。

回答

0

您必須爲您的PageCreateViewModel添加一個額外的字符串屬性。在這個屬性中,我們將存儲選定的值。可以說它的名字是「作者」。編輯:我注意到你在你的模型中有一個屬性,但給它一個這樣的嘗試。

下拉列表填充需要在您的視圖中看起來像這樣。

@Html.DropDownList("Author", Model.Authors) 
+0

感謝您的回覆,但它不起作用。我的控制器中的下拉菜單仍然沒有價值。 – Bronzato 2012-01-12 13:04:02

+0

@Bronzato您的模型中的其他值在返回時是否正確填充? – JoJa 2012-01-12 13:08:10

1

謝謝你們。我終於發現我的錯誤:它不是作者正確的屬性綁定,它必須是AuthorID!

<div class="editor-field">   
@Html.DropDownListFor(model => model.PageToCreate.AuthorID, Model.Authors, "Please select...")   
</div> 

無論如何。

+0

LOL ...你知道嗎,這是我第一次想到,但後來我認爲這是理所當然的事情,你必須交叉檢查....反正祝你好運 – 2012-01-12 13:26:39

相關問題