EF C#中如何用视图输入字段命名上传文件?解决空引用异常
问题原因
你遇到的NullReferenceException是因为在UploadFile方法里新建了一个空的IdentificationProduitViewModel实例,这个新实例的DesignationCommerciale属性没有任何值(为null),当你用它拼接文件名时就触发了空引用异常。你需要用的是视图提交过来的、包含用户输入值的ViewModel实例,而不是重新创建一个空的。
修复方案
1. 修改UploadFile方法,接收视图传过来的ViewModel
给方法参数加上IdentificationProduitViewModel model,移除内部新建空model的代码,直接使用传入的model属性:
public async Task<string> UploadFile(IFormFile file, IdentificationProduitViewModel model) { string resp = String.Empty; try { // 增加判断,确保文件存在且DesignationCommerciale不为空 if (file.Length > 0 && !string.IsNullOrEmpty(model.DesignationCommerciale)) { string x = model.DesignationCommerciale; string filename = x + Path.GetExtension(file.FileName); string path = Path.GetFullPath(Path.Combine(Directory.GetCurrentDirectory(), "UploadFds")); // 提前创建上传目录,避免目录不存在的异常 if (!Directory.Exists(path)) { Directory.CreateDirectory(path); } using (var filestream = new FileStream(Path.Combine(path, filename), FileMode.Create)) { await file.CopyToAsync(filestream); } resp = filename; } else { resp = String.Empty; } } catch(Exception) { throw; } return resp; }
2. 调用UploadFile时传入视图绑定的ViewModel
在HTTP POST方法里,把从视图提交过来的model(不是新建的)传给UploadFile:
// 这里的model是POST方法从视图绑定得到的实例,包含用户输入的DesignationCommerciale值 string tryupload = await UploadFile(file_fds, model); if (!String.IsNullOrEmpty(tryupload)) { TempData["uploadok"] = "Fichier chargé avec success !"; model.Fds_Filepath = tryupload; }
额外注意事项
- 确保视图里的
DesignationCommerciale字段使用asp-for="DesignationCommerciale"绑定,这样用户输入的值才能正确传到后台的ViewModel里。 - 可以给ViewModel的
DesignationCommerciale属性添加必填验证(比如[Required]特性),避免用户未输入就提交上传。
内容的提问来源于stack exchange,提问作者Jérôme DE PORRES
相关产品推荐
相关产品推荐

