MVC3下拉列表混乱

时间:2011-08-19 08:23:19

标签: entity-framework asp.net-mvc-3 binding drop-down-menu

我正在使用MVC3和EF 4.1并尝试编辑一个具有下拉列表的模型,该列表是对父对象的引用。以下是模型:

public class Section
{
    public Guid SectionId { get; set; }
    public string Title { get; set; }
    public virtual ICollection<Article> Articles { get; set; } 
}

public class Article
{
    public Guid ArticleId { get; set; }
    public DateTime? DatePosted { get; set; }
    public string Title { get; set; }
    public string ArticleBody { get; set; }
    public Section Section { get; set; }        
}

这是用于呈现编辑的GET部分的控制器操作:

public ActionResult Edit(Guid id)
{
    Article article = db.Articles.Find(id);
    var sections = db.Sections.ToList();
    var secIndex = sections.IndexOf(article.Section);
    ViewBag.SectionId = new SelectList(sections, "SectionId", "Title", secIndex);            
    return View(article);
}

和视图

@model CollstreamWebsite.Models.Article

@using (Html.BeginForm()) {
    @Html.ValidationSummary(true)
    <fieldset>
        <legend>Article</legend>
        @Html.HiddenFor(model => model.ArticleId)

        <div class="editor-label">
            @Html.LabelFor(model => model.DatePosted)
        </div>
        <div class="editor-field">
            @Html.EditorFor(model => model.DatePosted)
            @Html.ValidationMessageFor(model => model.DatePosted)
        </div>

        ...

        <div class="editor-label">
            @Html.LabelFor(model => model.Section)
        </div>
        <div class="editor-field">
            @Html.DropDownList("SectionId")
        </div>

        <p>
            <input type="submit" value="Save" />
        </p>
    </fieldset>
}

最后是编辑的POST动作

[HttpPost]
public ActionResult Edit(Article article)
{
    if (ModelState.IsValid)
    {
        db.Entry(article).State = EntityState.Modified;
        db.SaveChanges();
        return RedirectToAction("Index");
    }
    return View(article);
}

我遇到的问题是,当HttpPost Edit返回时,article.Section为null。如何强制View将Section绑定到正在编辑的文章。

任何帮助表示感谢。

1 个答案:

答案 0 :(得分:4)

不要将模型直接推到视图中。改为使用ViewModel。

这样的事情:

<强>视图模型

public class EditArticleViewModel
{

    ///All the properties for your Article
    ///The SelectListItems for your Sections

    public List<SelectListItem> Sections{ get; set; }
    public String SelectedSection{ get; set; } 


}

修改

[HttpGet]
public ActionResult Edit(Guid id)    
{

     EditArticleViewModel oEditArticleViewModel = new EditArticleViewModel();

     //Fill in the SelectLists
     List<SelectListItem> Sections= new List<SelectListItem>();
     Sections.Add(new SelectListItem() { Text = "TheSelectedSection", Value = SectionId.ToString(), Selected = true});     

     foreach(Section otherSection in AllPossibleSections)
     {
        Sections.Add(new SelectListItem() { Text = otherSection.Title, Value = otherSection.Id, Selected = false});
      }

      oEditArticleViewModel.Sections = Sections;


    return View(oEditArticleViewModel );
}

您的观点

@Html.DropDownListFor(model => model.SelectedSection, Model.Sections)
//All other needed properties with their textboxes etc.

编辑帖子

[HttpPost]
public ActionResult Register(EditArticleViewModel oPostedViewModel)
{
    if (ModelState.IsValid)
    {
       //Get the Article and fill in the new properties etc.
       //You can get the selectedSection from the SelectedSection Property, just cast it to a Guid.


        RedirectToAction("Index", "Home");
    }            

    //Something went wrong, redisplay the form for correction.
    //Make sure to fill in the SelectListItems again.
    return View(oPostedViewModel);
}

希望有所帮助