2009-04-19 91 views
1

我在不同的控制器中执行动作,需要在执行前检查一些条件。如果条件不符合,我希望用户被重定向到另一个页面,指导下一步该做什么(说明中将包含用户必须遵循的链接)。ASP.NET MVC - 通过传递一些数据重定向到控制器/动作

例如SendMessage消息()动作位于消息控制器:

public ActionResult SendMessage() 
{ 
    // check if user has enough credit 
    if (!hasEnoughCredit(currentUser)) 
    { 
     // redirect to another page that says: 

     // "You do not have enough credit. Please go to LinkToAddCreditAction 
     // to add more credit." 
    } 

    // do the send message stuff here 
} 

我想有一个通用的动作称为ShowRequirements()位于要求的控制器。

在SendMessage()动作中,我想设置要显示给用户的消息,然后将用户转发到ShowRequirements()操作。我只是不希望该消息出现在ShowRequirements操作的URL中。

有什么办法可以将这些数据传递给ShowRequirements()动作吗?

回答

0

好吧,我想我错了。正如约翰和安德鲁所提到的,我只需通过ViewData将数据传递给视图即可。

所以我在/ views/Shared中创建了一个RequirementsPage.aspx。现在,在任何一个动作我,我填写ViewData字典,并把它传递给RequirementsPage.aspx这样的:

public ActionResult SendMessage() 
{ 
    // check if user has enough credit 
    if (!hasEnoughCredit(currentUser)) 
    { 
     // redirect to another page that says: 
     ViewData["key1"] = "some message"; 
     ViewData["key2"] = "UrlToTheAction"; 
     return View("RequirementsPage"); 
    } 

    // do the send message stuff here 
} 
6

你可以把它放在传递给被重定向到的新动作的TempData [“message”]中。

+0

这可能是最好的解决方案,但它听起来就像你可能要重新考虑你的业务逻辑。为什么两个不相交的动作需要一起发生,通过重定向连接以便发生某些过程?也许你需要抽象一些代码? – 2009-04-19 22:34:17

相关问题