2017-05-04 29 views
-1

如何在MVC5中設置包含列表的ViewBag中的TextBox值?正如你可以看到我的名單是在Viewbag.photos,我想有photo.id在我的文本框,然後傳遞的每個值給控制器從MVC5中的ViewBag列表中設置TextBox值C#

@foreach (var photo in ViewBag.photos) 
    { 
      @if (@photo.comment != null) 
      { 
       <h6>@photo.comment</h6> 
      } 
      else 
      { 
       <h6> - </h6> 
      } 
      @Html.TextBox("photoID", @photo.id) 

    } 

嘗試這樣做,我收到一個錯誤:

Error CS1973 'HtmlHelper>' has no applicable method named 'TextBox' but appears to have an extension method by that name. Extension methods cannot be dinamically dispached.

也許還有另一種解決方法?

+1

請製作ViewModel並傳入,而不是使用ViewBag ... – Milney

回答

2

這是因爲ViewBag.photosdynamic對象。編譯器無法知道它的類型,因此您必須手動將其轉換爲原始類型。

例如:

@Html.TextBox("photoID", (int)photo.id) 

作爲一個方面說明(我不知道這是否會阻止你的代碼的工作,但它是很好的做法是這樣),你也有位太多@ S:對引用Visual Studio,once inside code, you do not need to prefix constructs like "if" with "@"。因此,最終的代碼如下:

@foreach (var photo in ViewBag.photos) 
{ 
    if (photo.comment != null) 
    { 
     <h6>@photo.comment</h6> 
    } 
    else 
    { 
     <h6> - </h6> 
    } 
    @Html.TextBox("photoID", (int)photo.id) 
} 

你也應該考慮使用,而不是ViewBag的ViewModels通過您的控制器和您的看法之間的數據。

相關問題