无法在mvc4中使用外键在数据库中插入我的下拉列表数据

时间:2016-01-08 16:50:59

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

我想用外键打包我的数据并将其发送到数据库。我使用控制器从数据库收集数据并在我的视图中显示,当我完成表单时无法将其发送到数据库并查看异常

我的控制器代码是

    public ActionResult Register()
    {
        testContext test = new testContext();
        List<SelectListItem> listselecteditem = new List<SelectListItem>();
        foreach (Gender item in test.genders)
        {
            SelectListItem selectlist = new SelectListItem()
            {
                Text = item.GenderType,
                Value = item.GenderID.ToString(),
            };
            listselecteditem.Add(selectlist);
        }
        ViewBag.Datalist = new SelectList(listselecteditem, "Value", "Text");
        return View();
    }

此控制器从数据库获取数据并发送到下拉列表

并且此控制器将我的数据保存在数据库中

    [HttpPost]
    [ValidateAntiForgeryToken]
    public ActionResult Register(Person p)
    {

        using (testContext test=new testContext())
        {

            if (ModelState.IsValid)
            {
                try
                {
                    test.persons.Add(p);
                    test.SaveChanges();
                    ViewBag.Message="Success";
                }
                catch (Exception ec)
                {

                    ViewBag.Message = ec.Message;
                }

            }
        }
        return View(p);
    }

这是我的观点

@model testmvc.Models.Person

<div class="container">
    <div class="row">
        <div class="pull-right col-sm-offset-3 col-sm-6">
            <div class="panel panel-default">
                <div class="panel-heading ">
                    <p>register</p>
                </div>
                <div class="panel-body">
                    @using (Html.BeginForm("Register", "RegisterLogin", FormMethod.Post, new { @class = "form-horizontal" }))
                    {

                        @Html.ValidationSummary(true)
                        <fieldset>
                            @Html.AntiForgeryToken()
                            @if (ViewBag.Messsage != null)
                            {
                                <div class="alert alert-success">
                                    <p>@ViewBag.Message</p>
                                </div>
                            }
                            <div class="form-group">
                                @Html.TextBoxFor(model => model.Fullname, new { @class = "form-control", @placeholder = "Full name" })
                            </div>
                            <div class="form-group">
                                @Html.TextBoxFor(model => model.Username, new { @class = "form-control input-sm", @id = "last_name", @placeholder = "Username" })
                            </div>
                            <div class="form-group">
                                @Html.TextBoxFor(model => model.EmailAddress, new { @class = "form-control input-sm", @id = "email", @placeholder = "Email address" })
                            </div>
                            <div class="form-group">
                                @Html.TextBoxFor(model => model.Password, new { @class = "form-control input-sm floatlabel", @id = "first_name", @placeholder = "Password" })
                            </div>
                            <div class="form-group">
                                @Html.TextBoxFor(model => model.Comfirmpassword, new { @class = "form-control input-sm", @id = "last_name", @placeholder = "confirmpassword" })
                            </div>
                            <div class="form-group">
                                @*<select>
                                        @foreach (var item in ViewBag.DataList)
                                        {
                                            <option>@item.Text</option>
                                        }
                                </select>*@
                                @Html.DropDownList("Datalist",String.Empty)
                            </div>
                            <div class="form-group">
                                @Html.TextBoxFor(model => model.Birthday, new { @class = "form-control input-sm", @id = "password_confirmation", @placeholder = "Birthday yyyy/dd/mm" })
                            </div>
                            <div>
                                <input type="submit" value="Register" class="btn btn-primary">
                            </div>
                        </fieldset>
                    }
                </div>
            </div>
        </div>
    </div>
</div>

和我的模型代码

public partial class Person
{
    [Key]
    public int personID { get; set; }
    [Required]
    public String Fullname { get; set; }
    [Required]
    public String Username { get; set; }
    [Required]
    public String Password { get; set; }
    [Required]
    [NotMapped]
    public String Comfirmpassword { get; set; }
    [Required]
    public String EmailAddress { get; set; }
    [DataType(DataType.DateTime)]
    [Required]
    public DateTime Birthday { get; set; }
    public int GenderID { get; set; }
    [ForeignKey("GenderID")]
    public virtual Gender Gender { get; set; }
}

[Table("Gender")]
public partial class Gender
{
    [Key]
    public int GenderID { get; set; }
    [Required]
    public String GenderType { get; set; }
    public virtual ICollection<Person> Persons { get; set; }
}

此例外表示没有任何带有&#34; Datalist&#34;的viewdata键。我该如何解决这个问题以及我的代码问题

1 个答案:

答案 0 :(得分:1)

您获得此异常的原因是因为在[HttpPost]内部操作,您没有填充ViewBag.Datalist属性,就像您在Get操作中所做的那样。由于您重新显示相同的视图,并且此视图需要此信息才能正确呈现下拉列表,因此您需要填充它。为避免重复,您可以将此逻辑放在单独的方法中:

private SelectList GetGenders()
{
    using (testContext test = new testContext())
    {
        List<SelectListItem> listselecteditem = new List<SelectListItem>();
        foreach (Gender item in test.genders)
        {
            SelectListItem selectlist = new SelectListItem()
            {
                Text = item.GenderType,
                Value = item.GenderID.ToString(),
            };
            listselecteditem.Add(selectlist);
        }
        return new SelectList(listselecteditem, "Value", "Text");
    }
}

你将在你的2个行动中打电话:

public ActionResult Register()
{
    ViewBag.Datalist = GetGenders();
    return View();
}

[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Register(Person p)
{
    using (testContext test = new testContext())
    {
        if (ModelState.IsValid)
        {
            try
            {
                test.persons.Add(p);
                test.SaveChanges();
                ViewBag.Message = "Success";
            }
            catch (Exception ec)
            {
                ViewBag.Message = ec.Message;
            }
        }
    }

    ViewBag.Datalist = GetGenders();
    return View(p);
}