来自DB的MVC4 DropDownList

时间:2014-01-22 12:53:18

标签: c# .net asp.net-mvc-4 viewdata asp.net-mvc-partialview

我正在尝试制作非常简单的论坛,但我遇到了DropDownList的问题。我有两个模型:

ForumThread.cs

public partial class ForumThread
{
    public ForumThread()
    {
        this.ForumCategory = new HashSet<ForumCategory>();
    }

    public int TH_ID { get; set; }
    public System.DateTime DATE { get; set; }
    public string TOPIC { get; set; }
    public string USER { get; set; }

    public virtual ICollection<ForumCategory> ForumCategory { get; set; }
}

ForumCategory.cs

public partial class ForumCategory
{
    public ForumCategory()
    {
        this.ForumThread = new HashSet<ForumThread>();
    }

    public int CA_ID { get; set; }
    public string CATEGORY { get; set; }
    public bool isSelected { get; set; }

    public virtual ICollection<ForumThread> ForumThread { get; set; }
}

我尝试用视图制作“创建”功能:

创建

@model AnimeWeb.Models.ForumThread

@{
ViewBag.Title = "Create";
}

<h2>New Thread</h2>

@using (Html.BeginForm()) {
@Html.AntiForgeryToken()
@Html.ValidationSummary(true)

<fieldset>

    <div class="editor-field">
        @Html.HiddenFor(model => model.TH_ID)
    </div>

    <div class="editor-label">
        TOPIC
    </div>
    <div class="editor-field">
        @Html.EditorFor(model => model.TOPIC)
        @Html.ValidationMessageFor(model => model.TOPIC)
    </div>
    <div class="editor-label">
        CATEGORY
    </div>
    <div class="editor-field">
       @Html.EditorFor(model => model.ForumCategory)
    </div>
    <p>
        <input type="submit" value="Create" />
    </p>
</fieldset>
}

PartialView for ForumCategory:

ForumCategory

@model AnimeWeb.Models.FORUMCATEGORY

@Html.HiddenFor(model => model.CA_ID)
@Html.HiddenFor(model => model.CATEGORY)

<div>
@Html.DropDownListFor(item => Model.CA_ID, ViewBag.CA_ID as SelectList, "-- Select --")
</div>

ForumController

public ActionResult Create()
    {
        var db = new MainDatabaseEntities();

        var viewModel = new ForumThread
        {
            ForumCategory = db.ForumCategory.Select(c => new { CA_ID = c.CA_ID, CATEGORY = c.CATEGORY, isSelected = false }).ToList().Select(g => new ForumCategory
            {
                CA_ID = g.CA_ID,
                CATEGORY = g.CATEGORY,
                isSelected = false
            }).ToList(),
        };


        return View(viewModel);
    }

    //
    // POST: /Forum/Create

    [HttpPost]
    public ActionResult Create(ForumThread forumthread, String user, int id)
    {
        var db = new MainDatabaseEntities();
        var newthread = new ForumThread
        {
            TH_ID = forumthread.TH_ID,
            DATE = DateTime.Now,
            TOPIC = forumthread.TOPIC,
            USER = forumthread.USER,
            ForumCategory = new List<ForumCategory>()
        };

        foreach (var selectedCategory in forumthread.FORUMCATEGORY.Where(c => c.isSelected))
        {
            var category = new ForumCategory { CA_ID = selectedCategory.CA_ID };
            db.ForumCategory.Attach(category);
            newthread.ForumCategory.Add(category);
        }

        db.ForumThread.Add(newthread);
        db.SaveChanges();
        return RedirectToAction("Index");
    }

它显然不起作用。我尝试在这个论坛上使用其他线程,但没有任何帮助。有人可以解释我如何使这项工作?

错误在于ForumCategory的部分视图:

The ViewData item that has the key 'CA_ID' is of type 'System.Int32' but must be of type 'IEnumerable<SelectListItem>'.

2 个答案:

答案 0 :(得分:1)

在PartialView for ForumCategory中,您的演员表不正确:

@Html.DropDownListFor(item => Model.CA_ID, ViewBag.CA_ID as SelectList, "-- Select --")

您必须使用可以在模型中的方法中实现的SelectList(ListListItem列表):

public List<SelectListItem> GetCategories()
{
    var db = new MainDatabaseEntities();
    List<SelectListItem> list = new List<SelectListItem>();

    // Add empty item if needed
    SelectListItem commonItem = new SelectListItem();
    commonItem.Text = "--- Select ---";
    commonItem.Value = "-1";
    commonItem.Selected = true;
    list.Add(commonItem);

    // Add items from Database
    foreach (ForumCategory fc in db.ForumCategory)
    {
        SelectListItem i = new SelectListItem();
        i.Text = fc.CATEGORY;
        i.Value = fc.CA_ID.ToString();
        list.Add(i);
    }
    return list;
}

然后你可以这样下拉:

@Html.DropDownList("DropName", Model.GetCategories())

代码的某些部分可能存在其他错误,我只是回答了您引用的错误

答案 1 :(得分:0)

在您的editortemplate中,您有:

ViewBag.CA_ID as SelectList

但是你没有显示你填充ViewBag的位置。相反,你可能想做这样的事情:

@Html.DropDownListFor(m => m.CA_ID, 
                      new SelectList(Model.ForumCategory, 
                                     "CA_ID", "CATEGORY", Model.CA_ID))

正如MVC3 DropDownListFor - a simple example?中所述。