简体   繁体   中英

Set TextBox value from ViewBag list in MVC5 C#

How can I set TextBox value in MVC5 from ViewBag which contains a list? As you can see my list is in Viewbag.photos and I want to have each value of photo.id in my TextBox and then pass it to controller

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

     }

Trying to do that I get an error:

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.

Maybe there's another workaround?

This is happening because ViewBag.photos is a dynamic object. The compiler cannot know its type, so you have to manually cast it to its original type.

For example:

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

As a side note (I'm not sure whether this will prevent your code from working, but it's good practice anyway), you also have bit too many @ s: to cite Visual Studio, once inside code, you do not need to prefix constructs like "if" with "@" . So your final code will look like:

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

You should also consider using ViewModels instead of ViewBag to pass data between your controllers and your views.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM