如果未选中复选框,则HTML Razor DropDowListFor将返回null

时间:2016-02-22 21:47:06

标签: c# html razor

我有一个用户创建表单已经停止工作,并且当取消选中Is_Supervisor复选框时,管理程序下拉列表的空值出错,但在选中它时效果很好。

以下是HTML代码:

<!DOCTYPE html>
@model WebLeaveRequest1.Models.AddUserModel

@using (Html.BeginForm("AddUser", "LeaveRequest"))
{
   <div class="form-group">
        <label for=Supervisor>Supervisor:</label>
       @Html.DropDownListFor(m => m.Supervisor, new SelectList(ViewBag.sup_list, "Text", "Value"), "")
    </div>
    <div class="form-group">
        <label for=Is_Supervisor> Is Supervisor:</label>
        @Html.CheckBoxFor(m => m.Is_Supervisor)
    </div>

    <input type="submit" value="Register" />
}

这是我的控制器和填充下拉列表的代码:

[HttpGet]
public ActionResult AddUser()
{
    Make_Sup();
    Make_Role();
    Make_Mentor();
    return View();
}

public void Make_Sup()
{
    var query = from entry in db.tbl_user
                where entry.is_supervisor.ToString() == "True"
                select new
                {
                    name = entry.first_name +" "+ entry.last_name,
                    userid = entry.userid
                };
    ViewBag.sup_list = new SelectList(query, "name", "userid");
}

此外,这是一个几乎相同的HTML页面,可以完美地运行同一个网站:

<!DOCTYPE html>
@model WebLeaveRequest1.Models.AddUserModel
@using (Html.BeginForm("EditUser_Edit", "LeaveRequest"))
{
    <div class="form-group">
        <label for="Userid">Userid: </label>
        @ViewBag.Userid
    </div>
    <div class="form-group">
        <label for=Supervisor>Supervisor: </label>
        @Html.DropDownListFor(m => m.Supervisor, new SelectList(ViewBag.sup_list, "Text", "Value"), new { @Value = ViewBag.Supervisor })
    </div>
    <div class="form-group">
        <label for=Is_Supervisor> Is Supervisor: </label>
        @Html.CheckBoxFor(m => m.Is_Supervisor, new { @Value = ViewBag.Is_Supervisor })
    </div>
    <input type="submit" value="Update" />
}

AddUserModel

 public class AddUserModel
    {
        public string Userid { get; set; }
        public string Password { get; set; }
        public string Password1 { get; set; }
        public string First_Name { get; set; }
        public string Last_Name { get; set; }
        public string Email { get; set; }
        public bool Is_Supervisor { get; set; }
        public string Supervisor { get; set; }
        public string Supervisor_Level { get; set; }
        public string Mentor { get; set; }
    }

1 个答案:

答案 0 :(得分:0)

您的SelectList未正确创建。 ViewBag.sup_list中的媒体资源名称不是“文字”和“价值”,而是nameuserid。这应该可以解决问题:

new SelectList(ViewBag.sup_list, "name", "userid")