MVC5 Dropdownlist静态数据提交时遇到麻烦

时间:2015-02-25 14:36:29

标签: asp.net-mvc-5

在视图文件中,我将数据添加到硬编码的下拉列表中。

查看:Create.cshtml

@Html.DropDownList("Gender", new List<SelectListItem>

             {
                new SelectListItem{ Text="Only Male", Value = "" },
                new SelectListItem{ Text="Only Female", Value = "" },
                new SelectListItem{ Text="Combined", Value = "" }
             }, htmlAttributes: new { @class = "form-control" })

这就是我在脚手架控制器中所拥有的:

控制器:EventsController.cs

public ActionResult Create()
    {
        ViewBag.HallID = new SelectList(db.Halls, "HallID", "Name");
        return View();
    }

    [HttpPost]
    [ValidateAntiForgeryToken]
    public ActionResult Create([Bind(Include = "EventsID,HallID,Name,Date_Of_Occurence,time,description,seats,Event_for_Gender,Event_Coordinator,Event_Coord_phone,Event_Coord_email,Event_for_Whom")] Events events)
    {
        if (ModelState.IsValid)
        {
            db.Events.Add(events);
            db.SaveChanges();
            return RedirectToAction("Index");
        }

        ViewBag.HallID = new SelectList(db.Halls, "HallID", "Name",  events.HallID);
        return View(events);
    }

这是基本模型。     型号:Events.cs:

    [Required]
    [Column(TypeName = "varchar")]
    [Display(Name = "Invite")]
    public string Event_for_Gender { get; set; }

我是MVC的新手。我知道这不是正确的编码形式。

问题:

- I have the data added to dropdown list but Whenever I submit the page, the validation message shows "This field is required".  
- I have tried the ViewData from controller, which is also resulting the same. 

请建议替代方案。

1 个答案:

答案 0 :(得分:1)

1:您的下拉列表必须与您希望它绑定的字段具有相同的名称。

2:你的价值总是空的

试试这个:

@Html.DropDownList("Event_for_Gender", new List<SelectListItem>

             {
                new SelectListItem{ Text="Only Male", Value = "Only Male" },
                new SelectListItem{ Text="Only Female", Value = "Only Female" },
                new SelectListItem{ Text="Combined", Value = "Combined" }
             }, htmlAttributes: new { @class = "form-control" })