1

Here is my Item class:

public class Item
{
    public int ItemId { get; set; }
    public string Name { get; set; }
    public virtual List<Tag> Tags { get; set; }
}

Here's my GET action:

//
// GET: /Home/AddItem/

public ActionResult AddItem()
{
    List<Tag> Tags = Db.Tags.ToList();

    ViewBag.Tags = new SelectList(Tags, "TagId", "Name");

    return View();
}

Here's my view:

@model MySite.Models.Item

@using (Html.BeginForm()) {
    //...

    @Html.ListBox("Tags")

    //...
}

Finally, here's my POST action:

//
// POST: /Home/AddItem/

[HttpPost]
public ActionResult AddItem(Item Item)
{
    //...

    List<Tag> NewItemTags = Item.Tags.ToList();

    //...
}

The problem is that Item.Tags.ToList() is always empty in the POST action... like the selected values of the ListBox aren't being sent at all.

Stuck here. Please help.

1 Answer 1

3

I am assuming that TagId is integer.

public class Item
{
    public int ItemId { get; set; }
    public string Name { get; set; }
    public virtual List<int> Tags { get; set; }
}

[HttpPost]
public ActionResult AddItem(Item Item)
{   
    List<int> NewItemTags = Item.Tags.ToList();
}

Also in View your ListBox should have Name = "Tags". If you are using ListBoxFor then no need to worry.

If still issue provide further information related to view.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.