Путаница в выпадающем списке MVC3 - PullRequest
0 голосов
/ 19 августа 2011

Я использую 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 привязать раздел к редактируемой статье.

Любая помощь приветствуется.

1 Ответ

4 голосов
/ 19 августа 2011

Не выдвигайте вашу модель прямо к вашему виду.Вместо этого используйте ViewModel.

Примерно так:

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


}

Редактировать Get

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

Надеюсь, это поможет

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...