如何在mvc中使用外键绑定下拉列表

时间:2016-10-18 05:45:53

标签: asp.net-mvc

试图绑定BrandName列下拉但我无法得到它..任何人都可以帮我解决这个问题。

这是我的代码:

public class ApplicationUser : IdentityUser
{
    [Column(Order = 1), ForeignKey("Brands")]
    public int BrandId { get; set; }
    public virtual Brands Brands { get; set; }
}

  public class Brands
{
    [Key]
    [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    public int Id { get; set; }
    public string BrandName { get; set; }
    public string ContactPerson { get; set; }
    public string ContactNumber { get; set; }
}

控制器代码:

public ActionResult Register()
{
    ViewBag.Name = new SelectList(context.Roles.Where(u => !u.Name.Contains("Admin"))
        .ToList(), "Name", "Name");
    return View();
}

Register.chstml代码:

@using (Html.BeginForm("Register", "Account", FormMethod.Post, new { @class   = "form-horizontal", role = "form" }))
{
@Html.AntiForgeryToken()
<h4>Create a new account.</h4>
<hr />
@Html.ValidationSummary()
<div class="form-group">
    @Html.LabelFor(m => m.UserName, new { @class = "col-md-2 control-label" })
    <div class="col-md-10">
        @Html.TextBoxFor(m => m.UserName, new { @class = "form-control" })
    </div>
</div>
<div class="form-group">
    @Html.LabelFor(m => m.Password, new { @class = "col-md-2 control-label"    })
    <div class="col-md-10">
        @Html.PasswordFor(m => m.Password, new { @class = "form-control" })
    </div>
</div>
<div class="form-group">
    @Html.LabelFor(m => m.ConfirmPassword, new { @class = "col-md-2 control-label" })
    <div class="col-md-10">
        @Html.PasswordFor(m => m.ConfirmPassword, new { @class = "form-control" })
    </div>
</div>
<div class="form-group">
    @Html.Label("User Role", new { @class = "col-md-2 control-label" })
    <div class="col-md-10">
        @Html.DropDownList("UserRoles", (SelectList)ViewBag.Name, " ", new { @class = "form-control" })
    </div>
</div>
 <div class="form-group">
    @Html.Label("Brand Id", new { @class = "col-md-2 control-label" })
    <div class="col-md-10">
        @Html.DropDownList("BrandId",(SelectList)ViewBag.BrandNamenew,"",new{ @class = "form-control" })
    </div>
</div>
<div class="form-group">
    <div class="col-md-offset-2 col-md-10">
        <input type="submit" class="btn btn-default" value="Register" />
    </div>
</div>

}

如何编写控制器和cshtml代码来绑定BrandId下拉列表

0 个答案:

没有答案