我有两个控制器:
public class AController : Controller
{
public ActionResult AControllerAction()
{
if (// BControllerAction reported an error somehow )
{
ModelState.AddModelError("error-key", "error-value");
}
...
}
}
public class BController : Controller
{
public ActionResult BControllerAction()
{
try{Something();}
catch(SomethingExceprion)
{
// here I need to add error info data,
// pass it to AController and redirect to
// AControllerAction where this error will be added
// to model state
}
}
}
我想我可以这样做:
public ActionResult BControllerAction()
{
try{Something();}
catch(SomethingException)
{
var controller = new AController();
controller.ModelState.AddModelError("error-key", "error-value");
controller.AControllerAction();
}
}
但我建议这将是架构破解方法,我不想这样做。除了传递模型对象之外,还有一些更简单,更安全的方法吗?
答案 0 :(得分:3)
根据您需要传递回控制器A的异常的详细信息,我会按照
的方式执行某些操作。public ActionResult BControllerAction()
{
try{Something();}
catch(SomethingException ex)
{
return RedirectToAction("AControllerAction", "AController", new { errorMessage = ex.Message() })
}
}
然后将被调用方法的签名更改为
public ActionResult AControllerAction(string errorMessage)
{
if (!String.IsNullOrEmpty(errorMessage))
{
//do something with the message
}
...
}
答案 1 :(得分:2)
您可以将重定向返回到AControllerAction。您可以使用TempData字典(类似于ViewData)在这样的调用中共享数据(以这种方式存储的数据将持久存储到同一会话中的下一个请求,如in this blog post所述。)
示例:
public class AController : Controller
{
public ActionResult AControllerAction()
{
if (TempData["BError"] != null)
{
ModelState.AddModelError("error-key", "error-value");
}
...
}
}
public class BController : Controller
{
public ActionResult BControllerAction()
{
try{Something();}
catch(SomethingExceprion)
{
TempData["BError"] = true;
return RedircetToAction("AControllerAction", "AController");
}
}
}