下拉列表值似乎没有进入MVC 5的数据库

时间:2016-04-27 21:59:45

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

我正在尝试创建一个下拉列表,让您指定员工所在的公司。下面是我的EmployeeViewModel。 CompanyId是一个外键约束数据库字段,链接到Company表。

private void myBackgroundWorker_DoWork(object sender, DoWorkEventArgs e)
{
    while(true)
    {
        if(checkconn == true)
        {
            labelcheck.Text = "Connected";
        }
        else
        {
            labelcheck.Text = "Not Connected";
        }
    }
}

员工控制人员的相关部分:

public class EmployeeViewModel
{
    public EmployeeViewModel()
    {

    }

    public EmployeeViewModel(Employee Employee, string CompanyName)
    {
        Initialize(Employee, CompanyName);   
    }

    public EmployeeViewModel(Employee Employee, CliFFEntities db)
    {
        Initialize(Employee, db.Companies.Find(Employee.CompanyId).Name);
    }

    private void Initialize(Employee employee, string CompanyName)
    {
        this.Id = employee.Id;
        this.Name = employee.Name;
        this.CompanyId = employee.CompanyId;
        this.InternalId = employee.InternalId;
        this.CompanyName = CompanyName;
    }


    public int Id { get; set; }
    public string Name { get; set; }
    public Nullable<int> InternalId { get; set; }

    [Display(Name = "Company")]
    public int CompanyId { get; set; }

    public String CompanyName { get; set; }

    //public List<Company> CompanyList { get; set; }
    public IEnumerable<SelectListItem> CompanyList { get; set; } //to be set in controller on an as-needed basis
}

我的创建视图的相关部分:

    // GET: Employees/Create
    public ActionResult Create()
    {
        var evm = new EmployeeViewModel();
        evm.CompanyList = new SelectList(db.Companies, "Id", "Name");
        return View(evm);
    }

所以这一切似乎都很好。事实上,当我查看帖子数据时,它甚至将CompanyId设置为正确的值,对应于数据库中的公司ID。

但是如果我在数据库端强制执行外键,则会抛出错误,因为CompanyId似乎没有将其放入Employee记录中。如果我关闭FK约束,则CompanyId只显示为0.

是什么给出的?

1 个答案:

答案 0 :(得分:0)

Welp,看起来我对MVC 5如此陌生,以至于我没有意识到像post方法这样的东西。这是我将其更改为将EmployeeViewModel映射回Employee:

   // POST: Employees/Create
    // To protect from overposting attacks, please enable the specific properties you want to bind to, for 
    // more details see http://go.microsoft.com/fwlink/?LinkId=317598.
    [HttpPost]
    [ValidateAntiForgeryToken]
    public ActionResult Create([Bind(Include = "Id,Name,CompanyId,InternalId")] EmployeeViewModel evm)
    {
        var employee = new Employee { Name = evm.Name, CompanyId = evm.CompanyId, InternalId = evm.InternalId };
        if (ModelState.IsValid)
        {
            db.Employees.Add(employee);
            db.SaveChanges();
            return RedirectToAction("Index");
        }

        return View(employee);
    }