【问题标题】:Create DropDownList in Razor Engine MVC在 Razor Engine MVC 中创建 DropDownList
【发布时间】:2013-08-16 09:07:38
【问题描述】:

我有一个页面用于在我的数据库中的某个表中插入新行。一个字段是同一个表中父级的外键。所以我想要一个 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?

【问题讨论】:

标签: asp.net asp.net-mvc-3 razor


【解决方案1】:

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

控制器:

    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")

【讨论】:

  • 谢谢您,您的解决方案是正确的:)
【解决方案2】:

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

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

【讨论】:

    猜你喜欢
    • 2019-01-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-07-17
    • 1970-01-01
    相关资源
    最近更新 更多