You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

HTTPGET视图中MVC Model为空,引发NullReferenceException求助

Fixing the System.NullReferenceException in Your List View

Hey there, let's break down why you're seeing that "Object reference not set to an instance of an object" error on line 47 where you have @foreach (var item in Model). The root cause is your view's Model is null—your controller isn't passing the actual carpet data the view needs to render the list.

Let's walk through the fixes step by step:

1. Update Your Controller to Pass the Correct Model

Looking at your controller snippet, you're only defining a Qualities dropdown list, but you're not fetching or passing the carpet collection that the view expects as its Model. Here's how to fix that:

public ActionResult ViewCarpets() 
{
    // 1. Fetch the actual carpet data you want to display in the list
    var carpetList = context.Carpets.ToList(); // Replace with your actual query logic
    
    // 2. Keep your Qualities dropdown logic (if needed for the view)
    IEnumerable<SelectListItem> Qualities = context.Qualities.Select(c => new SelectListItem
    {
        Text = c.QualityName, // Adjust property names to match your actual model
        Value = c.Id.ToString()
    });
    ViewBag.Qualities = Qualities; // Pass dropdown data via ViewBag if you need it in the view
    
    // 3. Pass the carpet collection as the Model to the view
    return View(carpetList);
}

2. Ensure Your View Declares the Correct Model Type

At the top of your view, make sure you're specifying the exact type of the Model so the view knows what to expect. For example, if your carpet model is named Carpet:

@model IEnumerable<YourProjectNamespace.Models.Carpet>

3. Add a Null Check in the View (Optional but Safe)

Even if you fix the controller, it's a good practice to handle cases where the data might be empty or null. Wrap your foreach loop in a null check to avoid future errors:

@if (Model != null)
{
    foreach (var item in Model)
    {
        // Your existing list item rendering logic here
    }
}
else
{
    <p>No carpets available to display.</p>
}

4. Verify Your Data Source

If you still run into issues, double-check that context.Carpets actually returns data. You can debug the controller method to confirm carpetList isn't null or empty—if it is, you might need to adjust your query or ensure your database has carpet records.


内容的提问来源于stack exchange,提问作者Arslan Ali

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.20 11:51:45