我在 asp.net mvc 中保存 master 的详细信息时遇到问题。
作为参考,我正在使用 nhibernate。
我在 Store 和 Employee 实体之间有一对多的关系。我分两步保存主文件和细节。您首先创建商店,保存它,然后创建员工。
这是两个类:
public class Store
{
public Store()
{
Employees = new List<Employee>();
}
public virtual int Id { get; set; }
public virtual string Name { get; set; }
public virtual IList<Employee> Employees { get; set; }
}
public class Employee
{
public virtual int Id { get; set; }
public virtual string Name { get; set; }
public virtual Store Store { get; set; }
}
因此,要创建商店,我在商店的控制器和视图中有以下代码:
public virtual ActionResult Create()
{
var model = new StoreModel();
return View(model);
}
[HttpPost]
public ActionResult Create(StoreModel model)
{
if (ModelState.IsValid)
{
Store entity = new Store(model);
Repository<Store> repository = new Repository<Store>();
repository.Create(entity);
return RedirectToAction("Index");
}
return View(model);
}
@model StoreModel
@{
ViewBag.Title = "Create store";
Layout = "~/Views/Shared/_Layout.cshtml";
}
<h2>
Create store
</h2>
@Html.ValidationSummary(true)
@using (Html.BeginForm())
{
<div>
@Html.LabelFor(store => store.Name)
</div>
<div>
@Html.TextBoxFor(store => store.Name)
@Html.ValidationMessageFor(store => store.Name)
</div>
<p>
<input type="submit" value="Create"/>
</p>
}
<div>
@Html.ActionLink("Back", "Index")
</div>
这很好,但我的问题是当我试图拯救员工时,商店总是 null。因此,要创建员工,我在员工的控制器和视图中有以下代码:
public virtual ActionResult Create(int storeId)
{
var model = new EmployeeModel();
Repository<Store> repository = new Repository<Store>();
model.Store = repository.Read(storeId);
return View(model);
}
[HttpPost]
public ActionResult Create(EmployeeModel model) //Problem here, store is null in the model
{
if (ModelState.IsValid)
{
Employee entity = new Employee(model);
Repository<Employee> repository = new Repository<Employee>();
repository.Create(entity);
return RedirectToAction("Index");
}
return View(model);
}
@model EmployeeModel
@{
ViewBag.Title = "Create employee";
Layout = "~/Views/Shared/_Layout.cshtml";
}
<h2>
Create employee
</h2>
@Html.ValidationSummary(true)
@using (Html.BeginForm())
{
<div>
@Html.LabelFor(employee => employee.Name)
</div>
<div>
@Html.TextBoxFor(employee => employee.Name)
@Html.ValidationMessageFor(employee => employee.Name)
</div>
<p>
<input type="submit" value="Create"/>
</p>
}
<div>
@Html.ActionLink("Back", "Index")
</div>
我究竟做错了什么?