首页 > 解决方案 > 对象引用未设置为用于 MVC 文件(图像)上传的对象实例

问题描述

我是 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 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# 新手谢谢

标签: c#asp.net-mvc

解决方案


请检查这个例子。

注意:在您的问题中,您可能忘记了form tag文件上传时需要表单标签,并具有所需的属性enctype = "multipart/form-data"

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

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>

控制器代码:

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

推荐阅读