如何使用mvc linq EF中的数据库结果填充下拉列表

时间:2011-03-16 02:46:42

标签: c# asp.net asp.net-mvc-3

这是我的控制器:

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

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

        return View();
    }

}

这是我的观点:

@model MatchGaming.Models.MatchModel

@ {     ViewBag.Title =“CreateMatch”; }

CreateMatch

@using(Html.BeginForm()){     @ Html.ValidationSummary(真)              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>

我希望我的MatchTypeId是从我的表MatchTypes填充的下拉列表。

1 个答案:

答案 0 :(得分:0)

我假设您的数据库中有一个具有Id字段和描述字段的MatchTypes表。您希望显示一个显示不同MatchType描述的下拉列表。

在模型中包含一个字段,该字段返回MatchTypes表中MatchTypes记录的集合。然后代替LabelFor执行此操作:

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