Search code examples
c#htmlasp.net-mvcviewbag

How to include values from object inside <label> html tag in ASP.NET MVC 5


I need to include value from object which comes from controller via ViewBag inside the <label> and <input> html tag. The following is which I used inside the view page:

foreach (var stockItem in ViewBag.joinqry2)
{
      <div class="col-md-2">
          <label style='font-weight:normal;' name='InstockID' value= 'stockItem.ItemName' ><span> @(stockItem.ItemName) </span></label>
          <input class='form-control input_field stockItem' name='labOrder.ConsumedInventories[ + i + ].ConsumedQuantity' type='number' id='" + data[i].Instock + "' min='0' value= '"+ stockItem.ConsumedQuantity + "'/>
     </div>
}

ViewBag.joinqry2:

{ ConsumedQuantity = 1, ItemName = "Streck Tube" }
{ ConsumedQuantity = 1, ItemName = "Bubble Wrap" }
{ ConsumedQuantity = 7000, ItemName = "Biohazard Bag" }
{ ConsumedQuantity = 1, ItemName = "Absorbent Papers" } 
{ ConsumedQuantity = 1, ItemName = "Test Tube" }    

StockItem contains ConsumedQuantity and ItemName values inside the foreach loop but I am still getting error like this below:

My error is:

An exception of type 'Microsoft.CSharp.RuntimeBinder.RuntimeBinderException' occurred in App_Web_euru3gao.dll but was not handled in user code

Additional information: 'object' does not contain a definition for 'ItemName'


Solution

  • You have to cast the item retrieved from the ViewBag. In your current implementation, stockItem is an object, therefore it does not contain a property ItemName.

    As BviLLe_Kid mentioned, the cleaner way is to use a ViewModel:

    public class ConsumedItemModel {
        public int ConsumedQuantity {get; set;}
        public string ItemName {get; set;}
    }
    

    In your cshtml file, use the @model directive to tell Razor which ViewModel to expect. If you need additional properties, create a ViewModel that also contains the collection of ConsumedItemModel as a property. The following assumes that you only pass the collection of ConsumedItemModel from the controller.

    @model IList<ConsumedItemModel>
    foreach (var stockItem in Model) {
        var name = stockItem.ItemName;
        var qty = stockItem.ConsumedQuantity;
        // render label and input
    }