DropDownListFor单击提交后找不到对象引用

时间:2017-03-21 21:02:23

标签: c# asp.net-mvc html.dropdownlistfor

我是MVC的新手,并尝试将表单数据传递回控制器,以便我可以使用数据。 Visual Studio在创建视图时有“创建”选项,在我开始使用DropDownListFor之前一直正常工作。

当视图第一次加载时,DropDownListFor加载正常,并且包含我从控制器传递给它的所有信息。但是,当我单击“提交”时,我得到“System.NullReferenceException:Object reference not not set to a object of object”。错误。我整天都在仔细研究,并没有找到解释。

以下是我项目的一些信息。

MODEL:

public class ApptDetails
{
    public IEnumerable<SelectListItem> CustomerNames { get; set; }
    public int[] CustomerIDs { get; set; }
    public int AppointmentID { get; set; }
    public DateTime ApptStart { get; set; }
    public DateTime ApptEnd { get; set; }
    public string LawyerName { get; set; }
    public string LawyerPhone { get; set; }
    public string FirmName { get; set; }
    public string FirmAddress { get; set; }
    public string FirmCity { get; set; }
    public string FirmState { get; set; }
    public string FirmZip { get; set; }
    public string ClientName { get; set; }
    public string OperatorPhone { get; set; }
    public string ClientVideoIP { get; set; }
    public decimal Rate { get; set; }
}

控制器:

    public ActionResult Create()
    {
        var model = new Models.ApptDetails();
        string sqlString = "SELECT CustomerID, CustomerName FROM [scheduling].[dbo].[customer]";

        List<SelectListItem> list = new List<SelectListItem>();

        using (SqlConnection myDB = new SqlConnection(ConfigurationManager.ConnectionStrings["appointmentdata"].ConnectionString))
        {
            myDB.Open();
            using (SqlCommand wsCommand = new SqlCommand(sqlString, myDB))
            {
                using (SqlDataReader wsReader = wsCommand.ExecuteReader())
                {
                    while (wsReader.Read())
                    {
                        SelectListItem one = new SelectListItem() { Text = wsReader.GetString(1), Value = wsReader.GetInt32(0).ToString() };
                        list.Add(one);
                    }
                }

            }
        }

        model.CustomerNames = list;

        return View(model);
    }

    [HttpPost]
    public ActionResult Create(ApptDetails appt)
    {
        ViewBag.Message = "Made it";

        return View();
    }

查看:

@using (Html.BeginForm()) {
    @Html.AntiForgeryToken()
    @Html.ValidationSummary(true)

    <fieldset>
        <legend>ApptDetails</legend>

        <div class="editor-label">
            @Html.LabelFor(model => model.LawyerName)
        </div>

        <div class="editor-field">
            @Html.DropDownListFor(model => model.LawyerName, Model.CustomerNames)
            @Html.ValidationMessageFor(model => model.LawyerName)
        </div>

        <p>
            <input type="submit" value="Create" />
        </p>
    </fieldset>
}

就像我说的那样......我的知识是有限的,所以如果这是一个基本问题我会道歉。提前感谢您提供的任何帮助!

0 个答案:

没有答案