.NET Core 2.0 MVC视图如何访问其他模型的属性?
Hey there! Let's get this sorted for you so your Member Index view shows that friendly membership type string instead of the raw numeric ID. Here's what you need to do:
Step 1: Make sure your Member model has a navigation property to MembershipType
First, double-check that your Member class includes a navigation property pointing to the related MembershipType entity. This lets Entity Framework link the two models together:
public class Member { public int Id { get; set; } public string Name { get; set; } // Your existing foreign key public int MembershipTypeId { get; set; } // Add this navigation property public MembershipType MembershipType { get; set; } }
(If you're using Code First, EF should automatically recognize the MembershipTypeId foreign key here since it follows the standard naming convention.)
Step 2: Load the related MembershipType data in your controller
When fetching members in your Index action, you need to explicitly include the related MembershipType data to avoid lazy loading delays or null reference issues. Use the Include method:
For EF 6:
using System.Data.Entity; // Don't forget this using statement public ActionResult Index() { var members = db.Members.Include(m => m.MembershipType).ToList(); return View(members); }
For EF Core:
using Microsoft.EntityFrameworkCore; // Required using statement public IActionResult Index() { var members = _context.Members.Include(m => m.MembershipType).ToList(); return View(members); }
This ensures each member comes with its associated membership type data ready to use, and avoids inefficient N+1 query issues.
Step 3: Update your view to display the friendly string
Now in your Index view's foreach loop, replace the line that displays @item.MembershipTypeId with a reference to the friendly property from the MembershipType navigation property. Add a null check too, just in case a member doesn't have a valid membership type assigned:
@foreach (var item in Model) { <tr> <td>@item.Name</td> <!-- Replace MembershipTypeId with your friendly property (e.g., Name/DisplayName) --> <td>@(item.MembershipType?.DisplayName ?? "No Membership Assigned")</td> <!-- Add your other member columns here --> <td> <a asp-action="Edit" asp-route-id="@item.Id">Edit</a> | <a asp-action="Details" asp-route-id="@item.Id">Details</a> | <a asp-action="Delete" asp-route-id="@item.Id">Delete</a> </td> </tr> }
Just swap DisplayName with whatever the actual property name is in your MembershipType model that holds the friendly string (like Name or MembershipTypeName).
That's it! Your view should now show the human-readable membership type instead of the numeric ID.
内容的提问来源于stack exchange,提问作者Metzer

