model-view-controllerdetailsview

MVC View Model show Detail Information


I hope this makes sense.

I created a class like the following that uses 3 tables (TerrRp, RegMg,DistMg) that I am using in View Model:

     public class RepViewModel  

{



    public IEnumerable<TerrRp> TerrRp { get; set; }
    public IEnumerable<RegMg> RegMg { get; set; }
    public IEnumerable<DistMg> DistMg { get; set; } 



}

I need to show the Detail info for one of the ables above (TerrRp table)and not sure how to do it as I am not able to access the fields in the
through something like (in this case I am trying to access the Terr_ID):

<div class="display-label">Terr_ID</div>
<div class="display-field">
    @Html.DisplayFor(model => model.Terr_ID)
</div>

Meaning, how can I tell DisplayFor to get a hold of the TerrRp table and show the Terr_ID as I need to access RepViewModel first then TerrRp then Terr_ID? Hope this makes sense.


Solution

  • To show a list of associated objects:

    Using a strongly typed view with the header

    @model namespace.RepViewModel  
    

    You should be able to wind through the TerrRp objects with

    @foreach (var Rp in Model.TerrRp)
    {
        <div class="display-label">Terr_ID</div>
        <div class="display-field">
            @Html.DisplayFor(Rp  => Rp.Terr_ID)
        </div>
    }
    

    If you believe that there should only be one object TerrRp associated with the RepViewModel then you could use either First() or FirstOrDefault() methods on IEnumerable

    <div class="display-label">Terr_ID</div>
    <div class="display-field">
        @Html.DisplayFor(model => model.TerrRp.FirstOrDefault().Terr_ID)
    </div>
    

    You may want to do a count on the Model.TerrRp object to verify that there is one and only one entry.