首页 > 解决方案 > 在 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);

我想补充一点,如果我删除按钮,那么一切都会正确保存,而且问题似乎只出在上传按钮功能上。

标签: c#asp.net-mvc

解决方案


推荐阅读