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

ASP.NET Core 6 MVC控制器数据无法传递至视图问题求助

ASP.NET Core MVC控制器无法传递CSV读取数据到视图的解决方案

问题背景

刚接触ASP.NET Core MVC,此前一直使用Web API。控制器中的数据无法传递到视图,但返回字符串等其他类型对象时代码正常运行。怀疑问题与CSV读取器有关,相关代码如下:

模型类

public class Personnel
{
    [Key]
    public int Id { get; set; }
    public string PayrollNumber { get; set; }
    public string Forename { get; set; }
    public string Surename { get; set; }
    public DateTime DateOfBirth { get; set; }
    public int Telephone { get; set; }
    public int Mobile { get; set; }
    public string Address { get; set; }
    public string Address2 { get; set; }
    public string Postcode { get; set; }
    public string EmailHome { get; set; }
    public DateTime StartDate { get; set; }
}

控制器代码

public class UploadController : Controller
{
    private readonly IDataContext _context;

    public UploadController(IDataContext context)
    {
        _context = context;
    }

    public IActionResult Index()
    {
        return View();
    }

    [HttpPost("Index")]
    public async Task<IActionResult> Index(IFormFile file)
    {
        var reader = new StreamReader(file.OpenReadStream());

        var csv = new CsvReader(reader, CultureInfo.GetCultureInfo("en-GB"));
        csv.Context.RegisterClassMap<PersonnelClassMap>();
        var records = csv.GetRecords<Personnel>();
        await _context.Personnel.AddRangeAsync(records);
        await _context.ContextSaveChanges();

        return View(records); 
    }
}

视图代码

@model IEnumerable<Web.Models.Personnel>

<div class="card">

    <h3 class="card-header text-center font-weight-bold text-uppercase py-4">
        Records inserted
    </h3>
    <div class="card-body">
        <div id="table" class="table-editable">
            <span class="table-add float-right mb-3 mr-2">
                <a href="#!" class="text-success"><i class="fas fa-plus fa-2x" aria-hidden="true"></i></a>
            </span>
            <table class="table table-bordered table-responsive-md table-striped text-center">
                <thead>
                    <tr>
                        @{
                            var properties = typeof(Personnel).GetProperties();
                            foreach (var property in properties)
                            {
                                if (property.Name == "Id")
                                {
                                    continue;
                                }
                                <th scope="col">@property.Name</th>
                            }
                        }
                    </tr>
                </thead>
                <tbody>
                    @if (Model != null)
                        {
                        foreach (var record in Model)
                            {
                                <tr>
                                <td class="pt-3-half" contenteditable="true">@record.Surename</td>

                                    <td class="pt-3-half">
                                        <span class="table-up">
                                            <a href="#!" class="indigo-text"><i class="fas fa-long-arrow-alt-up" aria-hidden="true"></i></a>
                                        </span>
                                        <span class="table-down">
                                            <a href="#!" class="indigo-text"><i class="fas fa-long-arrow-alt-down" aria-hidden="true"></i></a>
                                        </span>
                                    </td>
                                    <td>
                                        <span class="table-remove">
                                            <button type="button" class="btn btn-danger btn-rounded btn-sm my-0">
                                                Remove
                                            </button>
                                        </span>
                                    </td>
                                </tr>
                            }

                        }
                </tbody>
            </table>
        </div>
    </div>
</div>

解决步骤

1. 立即枚举CSV读取结果

CsvReader.GetRecords<T>()返回的是延迟加载的IEnumerable,调用AddRangeAsync时已遍历过一次数据流,到视图再遍历就无数据了。修改控制器代码,将结果转为List强制加载到内存:

var records = csv.GetRecords<Personnel>().ToList();
await _context.Personnel.AddRangeAsync(records);
await _context.ContextSaveChanges();

return View(records); 

2. 验证CSV映射正确性

检查PersonnelClassMap是否正确绑定CSV列与模型属性,若列名和属性名不一致,需显式指定:

public class PersonnelClassMap : ClassMap<Personnel>
{
    public PersonnelClassMap()
    {
        Map(m => m.PayrollNumber).Name("CSV中对应列名");
        Map(m => m.Forename).Name("CSV中对应列名");
        // 其他属性依次绑定对应列名
    }
}

3. 确认视图模型命名空间

确保视图顶部@model指令的命名空间与模型实际命名空间一致,避免类型不匹配导致绑定失败。

4. 调试验证数据读取状态

在控制器中添加逻辑确认CSV是否读取到数据:

var records = csv.GetRecords<Personnel>().ToList();
if (!records.Any())
{
    return View(new List<Personnel>()); // 处理无数据情况
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.27 13:22:05