MVC では、どこにリダイレクトするかを決定する責任がどこにあるのか疑問に思っています。コントローラーだと思いますが、よくわかりません。
の Create アクションで、WorkshopItem
渡された ViewModel から新しい WorkshopItem を作成し、それをデータベースに保存しています。ViewModel の一部はSelectedCustomerId
andです。SelectedCustomerIdCustomerName
が空で、名前が空の場合、default customer
エンティティを取得して項目に関連付けます。Id が空で名前が空でない場合、ユーザーは顧客を検索しましたが、一致するものが見つからなかったため、値を取得して新しい顧客レコードを作成し、それを添付します。
[NHibernateActionFilter]
[HttpPost]
public ActionResult Create(WorkshopItemCreateViewModel model)
{
try
{
Customer customer = null;
if (model.SelectedCustomerId == new Guid() &&
!string.IsNullOrWhiteSpace(model.CustomerName))
customer = CreateNewCustomer(model.CustomerName);
else if (model.SelectedCustomerId == new Guid() &&
string.IsNullOrWhiteSpace(model.CustomerName))
{
// Assign the System Valued customer if no customer was selected.
var id = Guid.Parse(ConfigurationManager.AppSettings["ValuedCustomerId"]);
customer = Session.QueryOver<Customer>()
.Where(c => c.Id == id)
.SingleOrDefault();
}
// other stuff
return RedirectToAction("Index");
これは正常に機能していますがRedirectToAction
、顧客レコードが作成されたかどうかにも依存したいと考えています。顧客が作成された場合、それには のみがありName
、CustomerId を渡す Customer Controller の Edit アクションにリダイレクトしたいからです (できると思います)。私の質問は、これが MVC で有効なのか、それとも他の場所で責任を負うべきなのかということです。
これは次のようになります。
[NHibernateActionFilter]
[HttpPost]
public ActionResult Create(WorkshopItemCreateViewModel model)
{
try
{
Customer customer = null;
bool newCustomer = false;
if (model.SelectedCustomerId == new Guid() &&
!string.IsNullOrWhiteSpace(model.CustomerName))
{
customer = CreateNewCustomer(model.CustomerName);
newCustomer = true;
}
else if (model.SelectedCustomerId == new Guid() &&
string.IsNullOrWhiteSpace(model.CustomerName))
{
// Assign the System Valued customer if no customer was selected.
var id = Guid.Parse(ConfigurationManager.AppSettings["ValuedCustomerId"]);
customer = Session.QueryOver<Customer>()
.Where(c => c.Id == id)
.SingleOrDefault();
}
// other stuff
if (newCustomer)
return RedirectToAction("Edit", "Customer", new {id=customer.Id});
else
return RedirectToAction("Index");