提交表单时,下拉列表没有值

时间:2012-01-12 12:47:13

标签: asp.net-mvc

我尝试在视图中使用下拉列表来显示作者(用户)列表。我可以填充此下拉列表并查看我视图中的内容。提交表单时,我在我的控制器中调试我的操作,在检查我的模型时,与我的下拉列表相关联的字段的值为空。

这是我的动作控制器(在显示我的视图之前):

    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; }
}

有什么想法吗?

感谢。

2 个答案:

答案 0 :(得分:1)

谢谢你们。我终于找到了我的错误:它不是Author的正确属性绑定,它必须是AuthorID !!

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

非常感谢。

答案 1 :(得分:0)

您必须向PageCreateViewModel添加额外的字符串属性。在此属性中,我们将存储选定的值。让我们说它的名字是“作者”。编辑:我注意到你的模型中有一个属性,但尝试这样。

下拉列表填充需要在您的视图中显示如下。

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