如何使用同一模型中的两个下拉菜单实例

本文关键字:两个 实例 下拉菜单 何使用 模型 | 更新日期: 2023-09-27 17:59:14

我遇到了一个问题,我认为我已经正确设置了,但结果总是为零。

以下是三种型号:

public class FamilyMember
{
    [Key]
    public int id { get; set; }
    [Required]
    [Display(Name = "First Name")]
    public string firstName { get; set; }
    [Required]
    [Display(Name = "Surname")]
    public string surname { get; set; }
    [Required]
    [Display(Name = "Date of Birth")]
    public DateTime dob { get; set; }
    public virtual FamilyRelationship FamilyRelationship { get; set; }
    [Display(Name = "Full Name")]
    public string fullName
    {
        get
        {
            return string.Format("{0} {1}", firstName, surname);
        }
    }
}
public class RelationshipType
{
    [Key]
    public int id { get; set; }
    [Required]
    [Display(Name="Relationship Type")]
    public string relationshipType { get; set; }
    public virtual FamilyRelationship FamilyRelationship { get; set; }
}
public class FamilyRelationship
{
    [Key]
    public int id { get; set; }
    [ForeignKey("FamilyMembers")]
    [Display(Name = "First Family Member")]
    public int familyMemberPrimary { get; set; }
    [ForeignKey("FamilyMembers")]
    [Display(Name = "Second Family Member")]
    public int familyMemberSecondary { get; set; }
    [Display(Name = "Relationship Type")]
    public int relationshipType { get; set; }
    public virtual ICollection<FamilyMember> FamilyMembers { get; set; }
    public virtual ICollection<RelationshipType> RelationshipTypes { get; set; }
}

因此,我已经成功地将数据添加到FamilyMemberRelationshipType,CRUD工作得很好。

问题出现在FamilyRelationship的创建控制器/视图中。下拉菜单工作得很好,在两个相关菜单中显示了家庭成员,关系也显示在relationType下拉菜单上。但是,当我单击create时,所有值都设置为null。

创建控制器:

    // GET: FamilyRelationships/Create
    public ActionResult Create()
    {
        ViewBag.familyMember = new SelectList(db.FamilyMembers, "id", "fullName");
        ViewBag.relationship = new SelectList(db.RelationshipTypes, "id", "relationshipType");
        return View();
    }
    // POST: FamilyRelationships/Create
    [HttpPost]
    [ValidateAntiForgeryToken]
    public ActionResult Create([Bind(Include = "id,familyMemberPrimary,familyMemberSecondary,relationshipType")] FamilyRelationship familyRelationship)
    {
        if (ModelState.IsValid)
        {
            db.FamilyRelationships.Add(familyRelationship);
            db.SaveChanges();
            return RedirectToAction("Index");
        }
        return View(familyRelationship);
    }

创建视图:

    @model FamilyTree.Models.FamilyRelationship
    @{
        ViewBag.Title = "Create";
    }
    <h2>Create</h2>

    @using (Html.BeginForm()) 
    {
        @Html.AntiForgeryToken()
        <div class="form-horizontal">
            <h4>FamilyRelationship</h4>
            <hr />
            @Html.ValidationSummary(true, "", new { @class = "text-danger" })
            <div class="form-group">
                @Html.LabelFor(model => model.familyMemberPrimary, htmlAttributes: new { @class = "control-label col-md-2" })
                <div class="col-md-10">
                    @*@Html.EditorFor(model => model.familyMemberPrimary, new { htmlAttributes = new { @class = "form-control" } })
                    @Html.ValidationMessageFor(model => model.familyMemberPrimary, "", new { @class = "text-danger" })*@
                    @Html.DropDownList("familyMember", null, htmlAttributes: new { @class = "form-control" })
                    @Html.ValidationMessageFor(model => model.familyMemberPrimary, "", new { @class = "text-danger" })
                </div>
            </div>
            <div class="form-group">
                @Html.LabelFor(model => model.familyMemberSecondary, htmlAttributes: new { @class = "control-label col-md-2" })
                <div class="col-md-10">
                    @Html.DropDownList("familyMember", null, htmlAttributes: new { @class = "form-control" })
                    @Html.ValidationMessageFor(model => model.familyMemberPrimary, "", new { @class = "text-danger" })
                </div>
            </div>
            <div class="form-group">
                @Html.LabelFor(model => model.relationshipType, htmlAttributes: new { @class = "control-label col-md-2" })
                <div class="col-md-10">
                    @Html.DropDownList("relationship", null, htmlAttributes: new { @class = "form-control" })
                    @Html.ValidationMessageFor(model => model.relationshipType, "", new { @class = "text-danger" })
                </div>
            </div>
            <div class="form-group">
                <div class="col-md-offset-2 col-md-10">
                    <input type="submit" value="Create" class="btn btn-default" />
                </div>
            </div>
        </div>
    }
    <div>
        @Html.ActionLink("Back to List", "Index")
    </div>
    @section Scripts {
        @Scripts.Render("~/bundles/jqueryval")
    }

请让我知道我哪里出了问题,如果可能的话,请提供一个例子来实现这一点。

如何使用同一模型中的两个下拉菜单实例

@Html.DropDownList("familyMember"

您需要使用最有可能是的实际属性名称

@Html.DropDownList("familyMemberPrimary"

您还必须重命名viewbag属性以匹配要显示的项目。。或使用下拉列表进行

@Html.DropDownListFor(a => a.familyMemberPrimary, (SelectList)ViewBag.familyMember , new { @class = "form-control" })

您还需要为familyMemberSecondary 添加一个下拉列表

@Html.DropDownListFor(a => a.familyMemberSecondary, (SelectList)ViewBag.familyMember , new { @class = "form-control" })

这应该会让你非常接近。。

@model FamilyTree.Models.FamilyRelationship
@{
    ViewBag.Title = "Create";
}
<h2>Create</h2>
@using (Html.BeginForm())
{
    @Html.AntiForgeryToken()
    <div class="form-horizontal">
        <h4>FamilyRelationship</h4>
        <hr />
        @Html.ValidationSummary(true, "", new { @class = "text-danger" })
        <div class="form-group">
            @Html.LabelFor(model => model.familyMemberPrimary, new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.DropDownListFor(a => a.familyMemberPrimary, (SelectList)ViewBag.familyMember, new { @class = "form-control" })
                @Html.ValidationMessageFor(model => model.familyMemberPrimary, "", new { @class = "text-danger" })
            </div>
        </div>
        <div class="form-group">
            @Html.LabelFor(model => model.familyMemberSecondary, new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.DropDownListFor(a => a.familyMemberSecondary, (SelectList)ViewBag.familyMember, new { @class = "form-control" })
                @Html.ValidationMessageFor(model => model.familyMemberSecondary, "", new { @class = "text-danger" })
            </div>
        </div>
        <div class="form-group">
            @Html.LabelFor(model => model.relationshipType, new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.DropDownListFor(a => a.relationshipType, (SelectList)ViewBag.relationship, new { @class = "form-control" })
                @Html.ValidationMessageFor(model => model.relationshipType, "", new { @class = "text-danger" })
            </div>
        </div>
        <div class="form-group">
            <div class="col-md-offset-2 col-md-10">
                <input type="submit" value="Create" class="btn btn-default" />
            </div>
        </div>
    </div>
}
<div>
    @Html.ActionLink("Back to List", "Index")
</div>
@section Scripts {
    @Scripts.Render("~/bundles/jqueryval")
}

确保在POST 失败后重新设置ViewBag属性

DotNetFiddle示例

这是预期的行为。记住Http是无状态的。因此,在返回视图之前,您需要重新加载下拉数据

 [HttpPost]
 [ValidateAntiForgeryToken]
 public ActionResult Create([Bind(Include = "id,familyMemberPrimary,familyMemberSecondary,
                                  relationshipType")] FamilyRelationship familyRelationship)
 {
     if (ModelState.IsValid)
     {
         db.FamilyRelationships.Add(familyRelationship);
         db.SaveChanges();
         return RedirectToAction("Index");
     }
    //Let's reload the data for dropdown.
    ViewBag.familyMember = new SelectList(db.FamilyMembers, "id", "fullName");
    ViewBag.relationship = new SelectList(db.RelationshipTypes, "id", "relationshipType");
    return View(familyRelationship);
 }

编辑:根据评论

FamilyRelationship中的值为familyMemberPrimary,familyMemberSecondary和relationshipType的值为0,其中I我希望每个人的身份证都能通过。

因为您正在为视图中的familyMemberPrimary属性使用EditorFor辅助方法。因此,如果您没有在该输入字段中填充值,它将具有默认值(0表示int类型)

如果希望用下拉选择(族成员)填充该属性,则应将下拉名称值指定为familyMemberPrimary,以便在发布表单时,模型绑定将所选选项值设置为familyMemberPrimary属性。

@Html.DropDownList("familyMemberPrimary", 
           ViewBag.familyMember as IEnumerable<SelectListItem>, 
           htmlAttributes: new { @class = "form-control" })