簡體   English   中英

來自數據庫的MVC4 DropDownList

[英]MVC4 DropDownList from DB

我正在嘗試建立一個非常簡單的論壇,但是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>'.

在您的PartialView for ForumCategory中,您的演員表不正確:

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

您必須使用一個SelectList(SelectListItem的列表),您可以在模型的方法中實現該列表:

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())

您的代碼的某些部分可能還有其他錯誤,我只是回答了您引用的那一部分

在編輯器模板中,您具有:

ViewBag.CA_ID as SelectList

但是您不會顯示填充ViewBag的位置。 相反,您可能想執行以下操作:

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

正如在MVC3 DropDownListFor中解釋的那樣-一個簡單的示例?

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM