Question

I'm trying to make very simple forum, but I have problem with DropDownList. I have two models:

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

I tried to make "Create" function with view:

Create

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

And 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");
    }

And it obviously doesn't work. I tried to use other threads on this forum but nothing helped. Could someone explain me how to make this work?

The error is in partial view of ForumCategory:

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

Solution

In your PartialView for ForumCategory, your cast is not correct:

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

You have to use a SelectList (List of SelectListItem) that you can implement for example in a method in your model:

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

And then you can have you dropdown like that:

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

There may be other errors in some parts of your code, I just answered to the one you quoted

OTHER TIPS

In your editortemplate, you have:

ViewBag.CA_ID as SelectList

But you don't show where you fill the ViewBag. Instead you might want to do something like this:

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

As also explained in MVC3 DropDownListFor - a simple example?.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top