C# 对象引用未设置为MVC文件(图像)上载对象的实例

C# 对象引用未设置为MVC文件(图像)上载对象的实例,c#,asp.net-mvc,C#,Asp.net Mvc,我是MVC新手,我在学习一个教程时遇到了这个错误 我遵循了教程中的每个步骤,但仍然得到相同的错误 下面是我的视图代码 @model _234CrudDemo.Models.ComplaintTicket <div class="form-horizontal"> <h4>ComplaintTicket</h4> <hr /> @Html.ValidationSummary(true, "", new { @class =

我是MVC新手,我在学习一个教程时遇到了这个错误

我遵循了教程中的每个步骤,但仍然得到相同的错误 下面是我的视图代码

@model _234CrudDemo.Models.ComplaintTicket

<div class="form-horizontal">
    <h4>ComplaintTicket</h4>
    <hr />
    @Html.ValidationSummary(true, "", new { @class = "text-danger" })
    <div class="form-group">
        @Html.LabelFor(model => model.Title, htmlAttributes: new { @class = "control-label col-md-2" })
        <div class="col-md-10">
            @Html.EditorFor(model => model.Title, new { htmlAttributes = new { @class = "form-control" } })
            @Html.ValidationMessageFor(model => model.Title, "", new { @class = "text-danger" })
        </div>
    </div>

    <div class="form-group">
        @Html.LabelFor(model => model.Message, htmlAttributes: new { @class = "control-label col-md-2" })
        <div class="col-md-10">
            @Html.EditorFor(model => model.Message, new { htmlAttributes = new { @class = "form-control" } })
            @Html.ValidationMessageFor(model => model.Message, "", new { @class = "text-danger" })
        </div>
    </div>

    <div class="form-group">
        @Html.LabelFor(model => model.Attachment, htmlAttributes: new { @class = "control-label col-md-2" })
        <div class="col-md-10">
            <input type="file" name="ImageFile" required />
        </div>
    </div>

    <div class="form-group">
        @Html.LabelFor(model => model.Ministry, htmlAttributes: new { @class = "control-label col-md-2" })
        <div class="col-md-10">
            @Html.EditorFor(model => model.Ministry, new { htmlAttributes = new { @class = "form-control" } })
            @Html.ValidationMessageFor(model => model.Ministry, "", new { @class = "text-danger" })
        </div>
    </div>

    <div class="form-group">
        <div class="col-md-offset-2 col-md-10">
            <input type="submit" value="Create" class="btn btn-default" />
        </div>
    </div>
</div>
这是我的模型课

public partial class ComplaintTicket
{
    public int Id { get; set; }
    public string Title { get; set; }
    public string Message { get; set; }
    [DisplayName("Upload Image")]
    public string Attachment { get; set; }
    public Nullable<int> Ministry { get; set; }

    public virtual mins mins { get; set; }

    public HttpPostedFile ImageFile { get; set; }
}
公共部分类投诉单
{
公共int Id{get;set;}
公共字符串标题{get;set;}
公共字符串消息{get;set;}
[显示名称(“上传图像”)]
公共字符串附件{get;set;}
公共可空部{get;set;}
公共虚拟分钟{get;set;}
公共HttpPostedFile图像文件{get;set;}
}
请问我如何解决这个问题,我在这里搜索解决方案并尝试给出的答案 以前类似的问题,但没有一个有效,它仍然给我同样的错误,需要帮助。 我是c的新手#
谢谢

您需要从控制器向
视图
传递
投诉单
的实例。在使用
HttpGet
Add
控制器方法中,可以执行以下操作:

返回视图(新投诉单());

而不是返回
View()
。这样,传递给视图的模型就不是
null

请检查此示例

注意:在您的问题中,您可能忘记了
表单标签
当上传文件时,表单标签是必需的,并且具有必需的属性
enctype=“multipart/form data”

除此之外,您还可以使用
jquery/ajax
或其他
插件
上传上传文件

cshtml
标记:

<div class="form-horizontal">
    <h4>ComplaintTicket</h4>
    <hr />
    @using (Html.BeginForm("Add", "ComplaintTicket", FormMethod.Post,
                              new { enctype = "multipart/form-data" }))
    { 
        @Html.ValidationSummary(true, "", new { @class = "text-danger" })
    <div class="form-group">
        @Html.LabelFor(model => model.Title, htmlAttributes: new { @class = "control-label col-md-2" })
        <div class="col-md-10">
            @Html.EditorFor(model => model.Title, new { htmlAttributes = new { @class = "form-control" } })
            @Html.ValidationMessageFor(model => model.Title, "", new { @class = "text-danger" })
        </div>
    </div>

    <div class="form-group">
        @Html.LabelFor(model => model.Message, htmlAttributes: new { @class = "control-label col-md-2" })
        <div class="col-md-10">
            @Html.EditorFor(model => model.Message, new { htmlAttributes = new { @class = "form-control" } })
            @Html.ValidationMessageFor(model => model.Message, "", new { @class = "text-danger" })
        </div>
    </div>

    <div class="form-group">
        @Html.LabelFor(model => model.Attachment, htmlAttributes: new { @class = "control-label col-md-2" })
        <div class="col-md-10">
            <input type="file" name="ImageFile" required />
        </div>
    </div>

    <div class="form-group">
        @Html.LabelFor(model => model.Ministry, htmlAttributes: new { @class = "control-label col-md-2" })
        <div class="col-md-10">
            @Html.EditorFor(model => model.Ministry, new { htmlAttributes = new { @class = "form-control" } })
            @Html.ValidationMessageFor(model => model.Ministry, "", new { @class = "text-danger" })
        </div>
    </div>

    <div class="form-group">
        <div class="col-md-offset-2 col-md-10">
            <input type="submit" value="Create" class="btn btn-default" />
        </div>
    </div>
    }
</div>

我对您的代码做了一些修改,您可以参考这些修改并在您的终端进行尝试。基本上,您需要注意目录存在与否的一些条件方法,以及对象referecenull与否

我已经在各个方面更新了你的代码。即使在将图像发布到控制器时需要使用enctype=“multipart/form data”,否则文件对象将始终保持空

如果还需要什么,请告诉我

.cshtml代码

模态类

公共部分类投诉单
{
公共int Id{get;set;}
公共字符串标题{get;set;}
公共字符串消息{get;set;}
公共字符串附件{get;set;}
公共可空部{get;set;}
公共HttpPostedFileBase映像文件{get;set;}
}

@SimplyGed没有,我尝试了solutionsimageModel——很可能是空的。检查值和路径,您就可以让它工作了。@Jawad请更好地解释,我不明白在您的控制器中,这一行导致了NullReferenceExceptions。。。string fileName=Path.GetFileNameWithoutExtension(imageModel.ImageFile.fileName);您需要检查为什么imageModel是null@YahbuezeMannesseh在HTML代码中,当控制器尝试使用
string fileName=Path.GetFileNameWithoutExtension(imageModel.ImageFile.fileName)行访问该属性时,您从不为
ImageFile
属性赋值
ImageFile属性为空-这会产生您看到的错误。请重新阅读原始链接,因为它提供了关于如何修复
NullReferenceException
的最佳建议,仍然会出现相同的错误,对象引用未设置为对象的实例。描述:执行当前web请求期间发生未处理的异常。请查看堆栈跟踪以了解有关错误的更多信息以及错误在代码中的起源。异常详细信息:System.NullReferenceException:Object reference未设置为对象的实例。请使用调试器并验证
imageModel
imageModel.ImageFile
不为空。请尝试
@Html.TextBoxFor(m=>m.ImageFile,new{type=“file”}而不是普通文件输入)
当我将HttpPostedFile更改为HttpPostedFileBase时,我的代码也可以正常工作。我不能高估你,因为我的名声不到15岁
<div class="form-horizontal">
    <h4>ComplaintTicket</h4>
    <hr />
    @using (Html.BeginForm("Add", "ComplaintTicket", FormMethod.Post,
                              new { enctype = "multipart/form-data" }))
    { 
        @Html.ValidationSummary(true, "", new { @class = "text-danger" })
    <div class="form-group">
        @Html.LabelFor(model => model.Title, htmlAttributes: new { @class = "control-label col-md-2" })
        <div class="col-md-10">
            @Html.EditorFor(model => model.Title, new { htmlAttributes = new { @class = "form-control" } })
            @Html.ValidationMessageFor(model => model.Title, "", new { @class = "text-danger" })
        </div>
    </div>

    <div class="form-group">
        @Html.LabelFor(model => model.Message, htmlAttributes: new { @class = "control-label col-md-2" })
        <div class="col-md-10">
            @Html.EditorFor(model => model.Message, new { htmlAttributes = new { @class = "form-control" } })
            @Html.ValidationMessageFor(model => model.Message, "", new { @class = "text-danger" })
        </div>
    </div>

    <div class="form-group">
        @Html.LabelFor(model => model.Attachment, htmlAttributes: new { @class = "control-label col-md-2" })
        <div class="col-md-10">
            <input type="file" name="ImageFile" required />
        </div>
    </div>

    <div class="form-group">
        @Html.LabelFor(model => model.Ministry, htmlAttributes: new { @class = "control-label col-md-2" })
        <div class="col-md-10">
            @Html.EditorFor(model => model.Ministry, new { htmlAttributes = new { @class = "form-control" } })
            @Html.ValidationMessageFor(model => model.Ministry, "", new { @class = "text-danger" })
        </div>
    </div>

    <div class="form-group">
        <div class="col-md-offset-2 col-md-10">
            <input type="submit" value="Create" class="btn btn-default" />
        </div>
    </div>
    }
</div>
public class ComplaintTicketController : Controller
{
    //CRUDDataComplaintsEntities db = new CRUDDataComplaintsEntities();
    //// GET: ComplaintTicket
    //public ActionResult Index()
    //{
    //    //var tickets = db.ComplaintsTickets.ToList();
    //    var tickets = (from x in db.ComplaintTicket
    //                   join a in db.mins on x.Ministry equals a.Id
    //                   select new TicketsIndexLists() { Id = x.Id, Title = x.Title, Message = x.Message, Attachment = x.Attachment, Name = a.Name }).ToList();
    //    return View(tickets);
    //}
    [HttpGet]
    public ActionResult Add()
    {
        return View();
    }

    [HttpPost]
    public ActionResult Add(ComplaintTicket imageModel,FormCollection formCollection)
    {
        try
        {
           // you can check with Request.Files.Count also
           // if(Request.Files.Count > 0) then your logic to save file
            if(imageModel.ImageFile!=null)
            {
                string fileName = Path.GetFileNameWithoutExtension(imageModel.ImageFile.FileName);
                string extension = Path.GetExtension(imageModel.ImageFile.FileName);
                fileName = fileName + DateTime.Now.ToString("yymmssfff") + extension;
                imageModel.Attachment = "~/Image/" + fileName;
                fileName = Path.Combine(Server.MapPath("~/Image/"), fileName);
                imageModel.ImageFile.SaveAs(fileName);
            }

            db.ComplaintTicket.Add(imageModel);
            db.SaveChanges();
            ModelState.Clear();
            //after save your return value
        }
        catch(Exception ex)
        {
        }

        return View();
    }
}
@model _234CrudDemo.Models.ComplaintTicket

<form method="post" action="@Url.Action(" Add ")" enctype="multipart/form-data">
  <div class="form-horizontal">
    <h4>ComplaintTicket</h4>
    <hr /> @Html.ValidationSummary(true, "", new { @class = "text-danger" })
    <div class="form-group">
      @Html.LabelFor(model => model.Title, htmlAttributes: new { @class = "control-label col-md-2" })
      <div class="col-md-10">
        @Html.EditorFor(model => model.Title, new { htmlAttributes = new { @class = "form-control" } }) @Html.ValidationMessageFor(model => model.Title, "", new { @class = "text-danger" })
      </div>
    </div>

    <div class="form-group">
      @Html.LabelFor(model => model.Message, htmlAttributes: new { @class = "control-label col-md-2" })
      <div class="col-md-10">
        @Html.EditorFor(model => model.Message, new { htmlAttributes = new { @class = "form-control" } }) @Html.ValidationMessageFor(model => model.Message, "", new { @class = "text-danger" })
      </div>
    </div>

    <div class="form-group">
      @Html.LabelFor(model => model.Attachment, htmlAttributes: new { @class = "control-label col-md-2" })
      <div class="col-md-10">
        <input type="file" name="ImageFile" required />
      </div>
    </div>

    <div class="form-group">
      @Html.LabelFor(model => model.Ministry, htmlAttributes: new { @class = "control-label col-md-2" })
      <div class="col-md-10">
        @Html.EditorFor(model => model.Ministry, new { htmlAttributes = new { @class = "form-control" } }) @Html.ValidationMessageFor(model => model.Ministry, "", new { @class = "text-danger" })
      </div>
    </div>

    <div class="form-group">
      <div class="col-md-offset-2 col-md-10">
        <input type="submit" value="Create" class="btn btn-default" />
      </div>
    </div>
  </div>
</form>
public class ComplaintTicketController : Controller
{
    //CRUDDataComplaintsEntities db = new CRUDDataComplaintsEntities();
    //// GET: ComplaintTicket
    //public ActionResult Index()
    //{
    //    //var tickets = db.ComplaintsTickets.ToList();
    //    var tickets = (from x in db.ComplaintTicket
    //                   join a in db.mins on x.Ministry equals a.Id
    //                   select new TicketsIndexLists() { Id = x.Id, Title = x.Title, Message = x.Message, Attachment = x.Attachment, Name = a.Name }).ToList();
    //    return View(tickets);
    //}
    [HttpGet]
    public ActionResult Add()
    {
        return View();
    }

[HttpPost]
        public ActionResult Add(ComplaintTicket imageModel)
        {
            if (imageModel.ImageFile != null)
            {
                string fileName = Path.GetFileNameWithoutExtension(imageModel.ImageFile.FileName);
                string extension = Path.GetExtension(imageModel.ImageFile.FileName);
                fileName = fileName + DateTime.Now.ToString("yymmssfff") + extension;
                imageModel.Attachment = "~/Image/" + fileName;
                string folderPath = Server.MapPath("~/Image/");
                if (System.IO.File.Exists(folderPath))
                {
                    fileName = Path.Combine(folderPath, fileName);
                    imageModel.ImageFile.SaveAs(fileName);
                }
                else
                {
                    System.IO.Directory.CreateDirectory(folderPath);
                    fileName = Path.Combine(folderPath, fileName);
                    imageModel.ImageFile.SaveAs(fileName);
                }
            }
            //db.ComplaintTicket.Add(imageModel);
            //db.SaveChanges();
            //ModelState.Clear();
            return View();
        }
}
public partial class ComplaintTicket
{
    public int Id { get; set; }
    public string Title { get; set; }
    public string Message { get; set; }
    public string Attachment { get; set; }
    public Nullable<int> Ministry { get; set; }
    public HttpPostedFileBase ImageFile { get; set; }
}