2013-05-31 40 views
0

我在BootstrapBaseController.csMVC4訪問一個控制器的方法將其他

public void Success(string message) 
{ 
    TempData.Add(Alerts.SUCCESS, message); 
} 

我沒有用它又一些內在的方法,但我想它表明我傳遞給該方法的一些成功消息。 我想在我的另一個名爲PortalController的控制器中使用這種方法。在下面的方法中,我想在用戶添加到數據庫時顯示成功消息。

對此提出建議?

[HttpPost] 
     public ActionResult Register(RegisterModel user) 
     { 
      if (ModelState.IsValid && (user.Password == user.ConfirmPassword)) 
      { 
       var regUser = _db.Users.Create(); 

       regUser.UserName = user.UserName; 
       regUser.Password = user.Password; 

       _db.Users.Add(regUser); 
       _db.SaveChanges(); 
      } 
      return View(); 
     } 

回答

0

你需要從BootstrapBaseController使PortalController繼承。

public class PortalController : BootstrapBaseController 

如果這不是一個選項,您可能需要將該常用方法移至由兩個控制器使用的第三個類。

+0

謝謝,但我只是意識到我沒有被轉發到[HttpPost]行動時,按下注冊按鈕。在點擊註冊按鈕時,它仍然會將我轉到[HttpGet]操作。可能需要作爲新的想法。 – Cybercop

+0

ummm如果我返回像這樣的返回RedirectToAction(「Index」,「Home」)到我的[httpPost] metod,我該如何顯示成功消息。我的註冊視圖使用_BootstrapLayout.empty.cshtml作爲佈局 – Cybercop

1
  1. 讓PortalController從BootstrapBaseController
  2. 繼承返回查看通話Sucess並設置消息
  3. 在您_layout.cshtml視圖(我假設你所有的觀點繼承使用此佈局)之前檢查該臨時變量和顯示您的消息

更新控制器方法:

[HttpPost] 
public ActionResult Register(RegisterModel user) 
{ 
    if (ModelState.IsValid && (user.Password == user.ConfirmPassword)) 
    { 
     var regUser = _db.Users.Create(); 

     regUser.UserName = user.UserName; 
     regUser.Password = user.Password; 

     _db.Users.Add(regUser); 
     _db.SaveChanges(); 
    } 
    Success("User Created successfully"); 

    return View(); 
} 

_Layout.cshtml

@if (TempData["VariableName"] != null) 
    { 
     <div>@TempData["VariableName"]</div> 
    } 
+0

實際上我使用另一種佈局,但我想我並沒有被''httpPost]''註銷''按鈕點擊'註冊'視圖。所以,在我解決這個問題之後,我會嘗試你提到的 – Cybercop

+0

ummm如果我返回像這樣的返回類似的東西,我該如何顯示成功消息?我的註冊視圖使用_BootstrapLayout.empty。 cshtml'作爲佈局 – Cybercop

+0

只需在代碼中檢查佈局上的TempData屬性即可。 TempData將可用並傳遞給新的操作 – amhed