我只是想知道,在 MVC 中,确定重定向位置的责任属于哪里。我认为是控制器,但我不确定。
在 a 的 Create 操作中,WorkshopItem
我从传入的 ViewModel 创建一个新的 WorkshopItem,然后将其保存到数据库中。ViewModel 的一部分是 a SelectedCustomerId
and CustomerName
,如果 SelectedCustomerId 为空且名称为空,我将获取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 (我想我能做到)。我的问题真的是在 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");