2015-12-11 44 views
0

我有一個邏輯問題需要回答!發佈數據時維護ViewBag值

這裏有一個場景..

- 在控制器

ViewBag.Name = "aaaa"; 

- 在查看

@ViewBag.Name 

「在我的控制,我有ViewBag設定值,並從獲取的值ViewBag in VIew。現在在View中,我有一個按鈕,它將一些數據發佈到一個HttpPost方法。在HttpPost方法中,我已經更改了ViewBag的值。在方法中,viewbag中的值會改變或不改變當前視圖??「

- 在HttpPost方法

ViewBag.Name="bbbb"; 
+0

它會改變。 – Icet

+0

值將在視圖中變化 –

+1

調試並檢查自己 – Imad

回答

5

您在操作方法上設置的ViewBag數據只能用於您正在使用的即時視圖。當您將它發回服務器時,除非將它保存在表單內的隱藏變量中,否則它將不可用。這意味着,你改變你的ViewBag數據的HttpPost操作方法後,你可以看到,在視圖中,您正在返回

public ActionResult Create() 
{ 
    ViewBag.Message = "From GET"; 
    return View(); 
} 
[HttpPost] 
public ActionResult Create(string someParamName) 
{ 
    ViewBag.Message = ViewBag.Message + "- Totally new value"; 
    return View(); 
} 

假設你的觀點是打印ViewBag數據

<h2>@ViewBag.Message</h2> 
@using(Html.BeginForm()) 
{ 
    <input type="submit" /> 
} 

結果將是

爲了您的GET Aciton,這將打印「From GET

用戶後提交年代的形式,將打印「Totally new value「;

如果您希望發佈之前的視圖包數據,請將其保存在隱藏的表單字段中。

<h2>@ViewBag.Message</h2> 
@using(Html.BeginForm()) 
{ 
    <input type="hidden" value="@ViewBag.Message" name="Message" /> 
    <input type="submit" /> 
} 

而你的行動方式,我們將接受隱藏字段的值以及

[HttpPost] 
public ActionResult Create(string someParamName,string Message) 
{ 
    ViewBag.Message = ViewBag.Message + "- Totally new value"; 
    return View(); 
} 

結果將是

爲了您的GET Aciton,這將打印 「From GET

用戶提交表格後,會打印「From GET-Totally new value」;

儘量避免像ViewBag/ViewData這樣的動態內容在動作方法和視圖之間傳輸數據。您應該使用強類型視圖和視圖模型模型。

4

ViewBag不下去的請求。帖子後存在的唯一數據是您發佈的數據,其中不包括ViewBag。不確定你的問題在這裏。

0

ViewBag值在[HttpGet][HttpPost]之間變化。

控制器代碼:

public class HomeController : Controller 
{ 
    public ActionResult Index() 
    { 
     ViewBag.Name = "Get!!!"; 
     return View(); 
    } 

    [HttpPost] 
    public ActionResult Index(int? id) 
    { 
     ViewBag.Name = "Post!!!"; 
     return View(); 
    } 
} 

查看代碼:

<h2>@ViewBag.Name</h2> 
@{Html.BeginForm("Index/1", "Home");} 
    <input type="submit" value="Submit" /> 
@{Html.EndForm();} 

的這個索引視圖的初始負載([HttpGet])示出了作爲ViewBag.Name 「獲取!!!」但在發佈後(點擊提交按鈕[HttpPost]ViewBag.Name顯示「發佈!!!」