1

我有一个用于在我的数据库中的某个表中插入新行的页面。一个字段是同一个表中父级的外键。所以我想要一个 drobdownlist 供用户选择父级。这是我的表定义:

Id          Integer
ParentId_Fk Integer
Body        Varchar
Title       Varchar

创建页面视图:

@model MVCDrLaptop.Models.Education

@{
    Layout = null;
}

<!DOCTYPE html>

<html>
<head>
    <title>Create</title>
</head>
<body>
    <script src="@Url.Content("~/Scripts/jquery-1.7.1.min.js")" type="text/javascript"></script>
    <script src="@Url.Content("~/Scripts/jquery.validate.min.js")" type="text/javascript"></script>
    <script src="@Url.Content("~/Scripts/jquery.validate.unobtrusive.min.js")" type="text/javascript"></script>

    @using (Html.BeginForm()) {
        @Html.ValidationSummary(true)
        <fieldset>
            <legend>Education</legend>

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

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

            <div class="editor-field">
                //here is for parentId_FK DropDownList
            </div>

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

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

那么我应该为创建我的 DropDownList 写什么?

4

2 回答 2

3

首先从数据库中获取所有值。

控制器:

    IEnumerable<SelectListItem> items = from value in values
                                        select new SelectListItem
                                        {
                                          Text = value.ToString(),
                                          Value = value.ToString(),
                                          Selected = value == selectedMovie,
                                         };
    ViewBag.MovieType = items;

看法:

    @Html.DropDownList("items")
于 2013-08-16T09:25:54.627 回答
3

@Html.DropDownListFor然后从模型中应用您需要的字段。

这是使用 DropDownList 和 DropDownListFor 的示例http://blinkingcaret.wordpress.com/2012/08/11/using-html-dropdownlistfor/

于 2013-08-16T09:11:40.423 回答