DropdownList选择的值未保存在数据库中

时间:2013-10-30 14:11:51

标签: asp.net sql-server asp.net-mvc-4 razor c#-5.0

我从这里需要大帮助我是Asp.net MVC 4应用程序开发的新手,实际上当我点击我的提交按钮后,我在数据库中保存我的下拉列表选择值时遇到了问题。

我使用Debug指针来检查HTTP post对象中的值,但是它不包含dropdownlist选择值它总是在一个部门中显示null值我需要一些专家建议来解决这个问题我通过几个例子尝试好几次,但我仍然没有适当的解决方案。

模特课:

public partial class tblEmployee
{
    public int EmployeeId { get; set; }
    public string Title { get; set; }
    public string FirstName { get; set; }
    public string LastName { get; set; }

    public Nullable<System.DateTime> DateOfBirth { get; set; }
    public Nullable<System.DateTime> DateOfJoin { get; set; }

    public string Position { get; set; }
    public string Office { get; set; }
    public string Division { get; set; }

    public Nullable<decimal> Salary { get; set; }
    public virtual tblDivision Divisions { get; set; }
}


public partial class tblDivision
{
    public int value { get; set; }
    public string Division { get; set; }
    public Nullable<int> SelectId { get; set; }
}

控制器类:

namespace EmpiteHrSystem.Controllers
{
    public class EmployeeController : Controller
    {
        private EmpiteContext db = new EmpiteContext();

        public ActionResult Create()
        { 
            ViewBag.DivisionOptions = new SelectList(db.tblDivisions, "value","Division");

            return View();
        }

        //
        // POST: /Employee/Create

        [HttpPost]
        public ActionResult Create(tblEmployee tblemployee)
        {
            if (ModelState.IsValid)
            {
                try
                { 
                    db.Entry(tblemployee).State = EntityState.Added;

                    db.tblEmployees.Add(tblemployee);
                    db.SaveChanges();
                }
                catch (ArgumentException ae)
                {
                    ModelState.AddModelError("", ae.Message);

                }
                return RedirectToAction("Index");
            }
        }
    }
}

查看:

@model EmpiteHrSystem.Models.tblEmployee
@{  ViewBag.Title = "Create"; Layout = "~/Views/Shared/_Layout.cshtml";}

@Html.EditorFor(model => model.EmployeeId) 

@Html.ValidationMessageFor(model => model.EmployeeId)

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

@*@Html.EditorFor(model => model.Office)*@

@Html.DropDownList("DivisionOptions")

@Html.ValidationMessageFor(model => model.Division)

@Html.ActionLink("Back to List", "Index")

1 个答案:

答案 0 :(得分:0)

您的DivisionOptions下拉列表未正确绑定到模型,因为它名称错误。当您的下拉列表绑定到 DivisionOptions 时,您的模型正在寻找名称为 Division 的媒体资源。你有几个选择。

  1. 使用强类型助手

    @ Html.DropDownListFor(x =&gt; x.Division,(SelectList)ViewBag.DivisionOptions)

  2. 重命名您的代码并传入SelectList

    @ Html.DropDownList(“Division”,(SelectList)ViewBag.DivisionOptions)