2016-03-23 91 views
0

爲什麼@Html.LabelFor(model => model.data, ((string)ViewBag.id)) 返回public ActionResult Index(Data item) null而不是100。如何解決這個問題?ASP.NET MVC ViewBag返回null

public ActionResult Index() 
    { 
     ViewBag.id = "100"; 
     return View(); 
    } 

    [HttpPost] 
    public ActionResult Index(Data item) 
    { 
     return View(); 
    } 

Index.cshtml

@model TestForm.Models.Data 
@{ 
    ViewBag.Title = "Index"; 
} 

<h2>Index</h2> 

@using(@Html.BeginForm()) 
{ 
    @Html.LabelFor(model => model.data, ((string)ViewBag.id)) 
    <input type="submit"/> 
} 
+3

'LabelFor()'不會生成表單控件。非常不清楚你想要做什麼,但是在將模型傳遞給視圖之前,需要在控制器中設置'model.data = 100;'的值,然後在視圖中使用'@ Html.TextBoxFor(m = > m.data)'(並刪除你的'ViewBag') –

+0

@StephenMuecke我認爲這就足夠了答案。 –

+0

因爲viewbag已經是字符串@ Html.LabelFor(model => model.data,ViewBag.id) –

回答

0

爲什麼@ Html.LabelFor(型號=> model.data,((串)ViewBag.id))在公衆的ActionResult指數(數據項)回報null而不是100

您從不在設置該方法中的值。如果您希望它在該方法之後顯示在標籤中,那麼您需要將ViewBag.id = "100";添加到該方法。

如果您試圖將該設置設置爲默認值,那麼您確實是錯誤地創建了表單。它應該是一個<%= Html.TextBoxFor(model => model.[fieldname], ViewBag.id))%>

然後這將被張貼回您的Data item對象並被設置。請注意,您必須更改[字段名稱]