c# - 在 asp.net c# 应用程序中上传文件的问题(对象引用未设置为对象的实例)
问题描述
我有一个模型:
public class Events
{
public int Id { get; set; }
public string title { get; set; }
public string amount { get; set; }
public string Finance_Approval { get; set; }
public string file_one { get; set; }
[NotMapped]
public HttpPostedFileBase file1 { get; set; }
}
控制器为:
public ActionResult Index()
{
return View();
}
public ActionResult Request(Events e)
{
string filename = Path.GetFileNameWithoutExtension(e.file1.FileName);
string extension = Path.GetExtension(e.file1.FileName);
filename = filename + DateTime.Now.ToString("yymmssfff") + extension;
e.file_one = "PM_Files/" + filename;
filename = Path.Combine(Server.MapPath("~/PM_Files/"), filename);
e.file1.SaveAs(filename);
_context.evt.Add(e);
_context.SaveChanges();
return Content("Added");
}
这是索引的完整 Razor 视图:
@model InsertFromdifferentControllers.Models.Events
@using (Html.BeginForm("Request", "Requester", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
<div class="form-group">
@Html.LabelFor(a => a.title)
@Html.TextBoxFor(a => a.title, new { @class = "form-control" })
</div>
<div class="form-group">
@Html.LabelFor(a => a.amount)
@Html.TextBoxFor(a => a.amount, new { @class = "form-control" })
</div>
<div class="form-group">
<label>Select the file word or pdf etc</label>
<input type="file" name="file1" />
</div>
<button class="btn btn-primary">Request</button>
}
当我单击请求按钮时,它会给出错误:对象引用未设置为对象的实例,并且将以红色标记以下行:
string filename = Path.GetFileNameWithoutExtension(e.file1.FileName);
我想补充一点,如果我删除按钮,那么一切都会正确保存,而且问题似乎只出在上传按钮功能上。
解决方案
推荐阅读
- android - 在构建发布 apk 时,任务“app:mergeReleaseResources”在本机反应中执行失败
- c# - 如何在读取文件时在 C# 中的列表/数组中添加多个元素,以便我可以在每行文本的一行上打印所有元素?
- laravel - 在 laravel 中提交后获取一个 vue 表单以转到下一页
- javascript - 在 Google 地图上显示多个多边形并切换每个多边形的可见性
- ios - 从 firebase 的观察者获取数据到另一个函数
- python - SyntaxError: 无效语法“url = ("https://etherscan.io/address/%s"address)
- apache-spark - SparkAppHandle 状态未在 Kubernetes 中更新
- karate - 如何设置基本 API?我看到从第一个 API 的响应中添加了双引号
- mysql - 在两个表中搜索列:ERROR 1066 (42000): Not unique table/alias
- html - 如何获取图像中光标位置的坐标?