【问题标题】:MVC -- creating Controller Action CreateNewEmployee in Northwind DBMVC——在 Northwind DB 中创建控制器动作 CreateNewEmployee
【发布时间】:2013-04-10 18:00:34
【问题描述】:

我尝试在 MVC 中创建一个新员工。 控制器:

HireEmployeeBL.EmployeeBL employeeBl = new HireEmployeeBL.EmployeeBL();

    public ActionResult HireNew(int id)
{
    return View();
}

[HttpPost]
public ActionResult HireNew(int id, Employee employee)
{
    employee.ReportsTo = new Manager { EmployeeID = id };
    employeeBl.AddEmployee(employee);
    return RedirectToAction("Subordinates");
    //return View();
}

服务器错误:

参数字典包含参数“id”的空条目 方法的不可空类型“System.Int32” 'System.Web.Mvc.ActionResult HireNew(Int32)' 在 'MvcEmployee.Controllers.EmployeeController'。可选参数 必须是引用类型、可空类型或声明为 可选参数。参数名称:参数

【问题讨论】:

  • 您是否将int 类型的ID 和Employee 类型的员工都传递给您的控制器操作?
  • 我已经编辑了你的标题。请参阅“Should questions include “tags” in their titles?”,其中的共识是“不,他们不应该”。
  • 是的,我将它们都传递给控制器​​动作
  • 您的视图/表单是什么样的?顺便说一句,你并没有同时传递它们......我并不是想变得粗鲁,但事实是,如果你传递一个 'id' 参数,你就不会得到那个错误。

标签: asp.net-mvc asp.net-mvc-4


【解决方案1】:
   [HttpPost]
        public ActionResult Create(Employee employee)
        {
            try
            {
                NorthwindEntities northwindEntities = new NorthwindEntities();
                northwindEntities.Employees.Add(employee);
                northwindEntities.SaveChanges(); 

                return RedirectToAction("Index");
            }
            catch
            {
                return View();
            }
        }

【讨论】:

  • 我忘记添加“HireEmployeeBL.EmployeeBL employeeBl = new HireEmployeeBL.EmployeeBL();”我使用employeeBl 而不是NorthwindEntities
  • 你必须调用 - northwindEntities.SaveChanges(); - 实际保存在数据库中。
  • 你真的应该把它提取到模型中,并尽可能地保持控制器内部的逻辑。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-05-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-06-12
  • 1970-01-01
相关资源
最近更新 更多