简体   繁体   中英

How to populate drop down with a database result in mvc linq EF

Here is my Controller:

public class MatchManagerController : Controller
{
    //
    // GET: /MatchManager/

    public ActionResult Index()
    {
        return View();
    }
    public ActionResult CreateMatch()
    {

        return View();
    }

}

Here is my View:

@model MatchGaming.Models.MatchModel

@{ ViewBag.Title = "CreateMatch"; }

CreateMatch

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

    <div class="editor-label">
        @Html.LabelFor(model => model.MatchName)
    </div>
    <div class="editor-field">
        @Html.EditorFor(model => model.MatchName)
        @Html.ValidationMessageFor(model => model.MatchName)
    </div>

    <div class="editor-label">
        @Html.LabelFor(model => model.MatchDescription)
    </div>
    <div class="editor-field">
        @Html.EditorFor(model => model.MatchDescription)
        @Html.ValidationMessageFor(model => model.MatchDescription)
    </div>

    <div class="editor-label">
        @Html.LabelFor(model => model.Wager)
    </div>
    <div class="editor-field">
        @Html.EditorFor(model => model.Wager)
        @Html.ValidationMessageFor(model => model.Wager)
    </div>

    <div class="editor-label">
        @Html.LabelFor(model => model.MatchTypeId)
    </div>
    <div class="editor-field">
        @Html.EditorFor(model => model.MatchTypeId)
        @Html.ValidationMessageFor(model => model.MatchTypeId)
    </div>

    <p>
        <input type="submit" value="Create" />
    </p>
</fieldset>
}

<div>

        @Html.ActionLink("Back to List", "Index")
    </div>

I want my MatchTypeId to be a drop down that populates from my table MatchTypes.

I'm assuming that you have a MatchTypes table in your database that has Id filed and Description field. You want to display a drop down that will show different MatchType descriptions.

Include a field in you model that returns collection of MatchTypes records from the MatchTypes table. Then instead of LabelFor do this:

@Html.DropDownListFor(m => m.Description, Model.MatchTypes)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM