未将对象引用设置为MVC文件(图像)上载的对象实例 [英] Object reference not set to an instance of an object for MVC file(image) upload

查看:85
本文介绍了未将对象引用设置为MVC文件(图像)上载的对象实例的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是MVC的新手,我正在学习一个教程,但遇到此错误

Am new to MVC, I was following a tutorial and got this error

我遵循了教程中的所有步骤,但是仍然遇到相同的错误 这是我的观点的代码

I followed the every steps in the tutorial, but still getting the same error Here is the code for my view

@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 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)
    {
        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();
        return View();
    }
}

这是我的模特班

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; }
}

请问我该如何解决,我在这里搜索解决方案并尝试给出答案 之前的类似问题,但都无济于事,它仍然给我同样的错误,需要帮助. 是C#的新手 谢谢

Please how do I resolve this, I have search for solutions here and try answers given to previous similar questions, but none worked for, its still giving me the same error, help needed. Am new to c# Thanks

推荐答案

我在您的代码中做了很少的修改,您可以参考一下并尝试一下.基本上,您需要注意目录是否存在以及对象引用是否为null的几种条件方法.

i have did few modification in your code, you can refer that and try on your end. Basically you need to take care few conditional approach for directory exists or not as well object referece null or not.

我已经全面更新了您的代码.即使在将图像发布到控制器时甚至需要使用 enctype ="multipart/form-data" ,否则文件对象将始终为null.

I have update you code with all aspect. Even you need to use enctype="multipart/form-data" while you post the image to controller, otherwise file object will remain null always.

如果有其他要求,请通知我.

Let me know in case of anything else required.

.cshtml代码

.cshtml Code

@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>

控制器代码

Controller Code

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; }
}

这篇关于未将对象引用设置为MVC文件(图像)上载的对象实例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆