-1

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

我使用调试指针检查 HTTP post 对象中的值,但它不包含下拉列表选择值它总是在除法原始中显示空值我需要一些专家建议来解决这个问题我通过几个示例并尝试了几次但是我仍然没有适当的解决方案。

型号类:

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")
4

1 回答 1

0

您的DivisionOptions下拉列表没有正确绑定回模型,因为它是错误的名称。当您的下拉列表绑定到DivisionOptions时,您的模型正在寻找名称为 Division 的属性。你有几个选择。

  1. 使用强类型助手

    @Html.DropDownListFor(x=>x.Division, (SelectList)ViewBag.DivisionOptions)

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

    @Html.DropDownList("Division", (SelectList)ViewBag.DivisionOptions)

于 2013-10-30T14:30:25.640 回答