Bv202
Bv202

Reputation: 4044

Create dropdown list of table

I currently have a table of series. In this table, a field status_id exists, which is the foreign key linking to a table Status. A status can be new, running, ended,...

My model classes are looking like this:

public partial class Serie
{
    public Serie()
    {
        this.Episodes = new HashSet<Episode>();
    }

    public int ID { get; set; }
    public string Name { get; set; }
    public string Country { get; set; }
    public Nullable<int> Status_id { get; set; }

    public virtual ICollection<Episode> Episodes { get; set; }
    public virtual Status Status { get; set; }
}

Status:

public partial class Status
{
    public Status()
    {
        this.Series = new HashSet<Serie>();
    }

    public int ID { get; set; }
    public string Name { get; set; }

    public virtual ICollection<Serie> Series { get; set; }
}

When editinga serie, I'd like to have a dropdown list of all possible statuses (the name field) and receive this when a user submits the form. What's the best way to accomplish this?

Upvotes: 1

Views: 519

Answers (2)

Dave Alperovich
Dave Alperovich

Reputation: 32500

The simplest answer is that you need to a List of Executives, pass the list in a model back to your View, create a select list, and render a drop down list.

public ActionResult EditSomething()
{
    Model Model = new Model();
    Model.statusList = {some method to fill IEnumerable<status>};

    return View(Model);
}

In your View:

@Html.DropDownListFor(model => model.Id, new SelectList(Model.statusList, "Id", "Name "))

Upvotes: 1

Ryan Byrne
Ryan Byrne

Reputation: 860

You need to create the dropdown list using <%= Html.DropDownList("StatusId", Model.Statuses)%>. You would populate your view model with all possible statuses, the record the id of the status the user selected in a variable that gets sent with your view model when the user submits the form. Here is an article detailing the process: http://odetocode.com/blogs/scott/archive/2010/01/18/drop-down-lists-and-asp-net-mvc.aspx

Upvotes: 0

Related Questions