ASP.NET MVC视图空引用异常求助:无法显示控制器传递的数据
Hey Karim, let's break down why you're hitting that System.NullReferenceException and get your view displaying data correctly. Here are the key issues to check and fixes to implement:
1. Verify your controller passes a fully initialized model
The most common cause here is that your controller action isn't creating an instance of GRHModel.ListeDemandeConger or populating its ldc property before sending it to the view.
Your controller code should look something like this:
public ActionResult AfficherMesDemandes() { // Create and initialize the model object var demandeModel = new GRHModel.ListeDemandeConger(); // Populate the ldc collection with your actual data (e.g., from a database) demandeModel.ldc = YourDataService.GetUserCongerDemands(); // Replace with your data fetch logic // Pass the ready model to the view return View(demandeModel); }
If you call return View() without passing a model, or forget to assign ldc, the Model in your view will be null (or Model.ldc will be null), which triggers the exception.
2. Add null checks to your view for safety
Even if you fix the controller, it's smart to handle edge cases where the model or collection might be empty. Update your view to include guard clauses:
@model GRHModel.ListeDemandeConger @{ ViewBag.Title = "AfficherMesDemandes"; Layout = "~/Views/Home/Common.cshtml"; } <table class="table table-responsive" style="width:400px"> @if (Model != null && Model.ldc != null) { foreach (var dc in Model.ldc) { <tr> <td> @Html.DisplayFor(i => dc.DateDebut) </td> </tr> } } else { <tr> <td>Aucune demande de congé trouvée.</td> </tr> } </table>
This way, if the model or ldc is ever null, you'll show a friendly message instead of a crash.
3. Ensure your ListeDemandeConger class initializes the ldc collection
Another frequent issue is that the ldc property in your model class isn't initialized by default. Add a constructor to your model to avoid this:
public class ListeDemandeConger { public ListeDemandeConger() { // Initialize the collection to prevent null references ldc = new List<YourCongerDemandType>(); // Replace with your actual entity type } public List<YourCongerDemandType> ldc { get; set; } }
This ensures that even if your controller doesn't populate ldc, the property won't be null — your loop will just iterate over an empty collection without errors.
Start with checking your controller's model initialization — that's almost always the root cause here. Let me know if you need further help after trying these steps!
内容的提问来源于stack exchange,提问作者karim merdessi

