マスターの詳細をasp.netmvcに保存する際に問題が発生しました。
参考までに、私はnhibernateを使用しています。
ストアエンティティと従業員エンティティの間には1対多の関係があります。マスターと詳細を2つのステップで保存します。最初にストアを作成して保存し、次に従業員を作成します。
両方のクラスは次のとおりです。
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>
私は何が間違っているのですか?