ASP.NET MVC3 model binding using IEnumerable (cannot infer type from)

I have a class model (edited for brevity)

Model class

public class GridModel { public string ItemNumber { get; set; } public int OnHandQty { get; set; } } public class Shipment { public string shipTrackingNo {get; set;} public IEnumerable<GridModel> ItemsShipped { get; set;} { 

cshtml page

 @model Namespc.Models.Shipment <link href="../../Content/CSS/Grid/Grid.css" rel="stylesheet" type="text/css" /> <script src="../../Scripts/ECommerce.Grid.js" type="text/javascript"></script> <div id="_shipmentDetailGrid"> <table class="TableStyle"> <tr class="GridRowStyle"> <td width="130px" ></td> @foreach (var Item in Model.ItemsShipped) { <td width="70px" align="center"> @html.LabelFor(item.OnHandQty) <-- Cannot infer type from usage </td> } </tr> 

I want to be able to bind item.OnHandQty, which is in the IEnumerable collection. How can you have a Model class, as well as an IEnumerable collection of a custom class (or rather, your own class)?

-1
source share
2 answers

Well, what is the type of items stored in ItemsShipped ? You should use the generic version of IEnumerable to indicate which types are stored in it.

If your class was named Item , you would declare it IEnumerable<Item> , then when iterated at runtime, i.e. @foreach (var Item in Model.ItemsShipped) , the type of Item will be strongly typed instead of a simple object .

+2
source

Instead of this:

 @foreach (var Item in Model.ItemsShipped) { <td width="70px" align="center"> @html.LabelFor(item.OnHandQty) <-- Cannot infer type from usage </td> } 

Do it:

 @Html.DisplayFor(model => model.ItemsShipped) 

Then create a custom display template (placed in Views/Shared/DisplayTemplates/GridModel.cshtml ):

 @model Namespc.Models.GridModel <td width="70px" align="center"> @html.LabelFor(model => model.OnHandQty) </td> 

I have a feeling that this does not work because you are not passing the expression to the LabelFor method.

The above is much better and more reliable than the explicit for loop.

0
source

Source: https://habr.com/ru/post/890158/


All Articles