2013-04-10 52 views
0

我嘗試在MVC中創建一個新的Employee。 控制器:MVC - 在Northwind DB中創建控制器操作CreateNewEmployee

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(); 
} 

服務器錯誤:

The parameters dictionary contains a null entry for parameter 'id' of non-nullable type 'System.Int32' for method 'System.Web.Mvc.ActionResult HireNew(Int32)' in 'MvcEmployee.Controllers.EmployeeController'. An optional parameter must be a reference type, a nullable type, or be declared as an optional parameter. Parameter name: parameters

+0

你路過這兩個類型'int'的ID和類型Employee'的'員工到控制器的動作? – 2013-04-10 18:12:55

+1

我編輯了你的標題。請參閱:「[應該在其標題中包含」標籤「](http://meta.stackexchange.com/questions/19190/)」,其中的共識是「不,他們不應該」。 – 2013-04-10 18:26:40

+0

是的,即時通過他們兩人控制器行動 – 2013-04-10 18:38:35

回答

0
[HttpPost] 
     public ActionResult Create(Employee employee) 
     { 
      try 
      { 
       NorthwindEntities northwindEntities = new NorthwindEntities(); 
       northwindEntities.Employees.Add(employee); 
       northwindEntities.SaveChanges(); 

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

我忘了添加「HireEmployeeBL.EmployeeBL employeeBl = new HireEmployeeBL.EmployeeBL();」我使用employeeBl而不是NorthwindEntities – 2013-04-10 18:32:20

+0

,你必須調用 - northwindEntities.SaveChanges(); - 實際上將其保存在數據庫中。 – marko 2013-04-12 05:10:35

+0

實際上,您應該將其提取到模型中,並將控制器內部的邏輯保持儘可能薄。 – marko 2013-04-12 05:11:47