2017-04-06 18 views
-2

我只是想要一些東西,我一直在我的很多代碼中實現,我認爲這不是做事的最佳方式。基於某種邏輯顯示和隱藏MVC視圖的部分的最佳方式是什麼?

您知道,在您提交表單後,您可能希望直接回到同一頁面並顯示成功消息,並希望隱藏提交的表單輸入,例如。其他時候,您可能會直接進入帶有可選參數的頁面,如查詢字符串,並且基於該參數,您可能想要在視圖上顯示和隱藏某些內容。

我不確定這樣做的最好方法,因爲我喜歡將所有邏輯放在控制器中,而不是將邏輯放在我的視圖中。

你可以簡單地通過在不同的面板中分離你的元素並在你的cs控件中設置隱藏屬性來完成這一點。

我一直在MVC(我不喜歡)中這樣做的方式是,例如,ViewBag成功消息和if語句在我的視圖中檢查viewbag是否爲空。如果不爲空,則顯示成功消息;否則,它會顯示一些表單輸入。其他時候,你不使用視圖包。例如,購物車的結賬頁面。在您看來,您可能會檢查購物車模型是否爲空。如果是,則顯示「抱歉,您的購物車是空的」消息;否則,顯示購物車表。在我看來,我不喜歡處理這個問題。什麼是最好的解決方案?還有其他解決方案嗎?

這裏有一些示例代碼。

控制:

[HttpPost] 
public ActionResult Edit(Elephants elephants) 
{ 
    // do something with elephants 

    ViewBag.weldone = "Weldone, you have made a wonderful impact by submitting this crucial knformation about elephants to the world"; 
    return View(); 

} 

查看:

@if(ViewBag.weldone != null) 
{ 
     <p>@ViewBag.weldone</p> 
} 

else 
{ 
     //something you want to hide from the page on succesfull elephant save 

} 

回答

1

不要使用ViewBag,使用視圖模型,而不是 - 其所謂的 「模型視圖控制器」 的一個原因。

public class Elephants 
{ 
    ... 
    public string SuccessMessage { get; set; } 
} 

[HttpPost] 
public ActionResult Edit(Elephants model) 
{ 
    // do something with elephants 

    model.SuccessMessage = "yay"; 
    return View(model); 
} 

,並在視圖

@model Elephants 

@if (model.SuccessMessage != null) 
{ 
    <p>@model.SuccessMessgae</p> 
} 
else 
{ 
    // Redisplay Elephants 
} 

@Html.ValidationSummary() 

,或者你可以避開所有通過重定向到顯示您的消息的另一頁。

[HttpPost] 
public ActionResult Edit(Elephants model) 
{ 
    // do something with elephants 

    return RedirectToAction("EditSuccess"); 
} 

[HttpGet] 
public ViewResult EditSuccess() 
{ 
    return View(); // Displays view "EditSuccess.cshtml" 
} 
相關問題