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

标签 c# asp.net-mvc

<分区>

我是 MVC 的新手,我正在学习教程并遇到了这个错误

Image Here

我按照教程中的每一步操作,但仍然出现相同的错误 这是我的 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>

这是我的 Controller

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

最佳答案

请检查这个例子。

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

除此之外,您还可以使用 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>

Controller 代码:

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

关于c# - 对象引用未设置为 MVC 文件(图像)上传的对象实例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59278607/

相关文章:

c# - Entity Framework : after SaveChanges returned object doesn't have children

c# - 用正则表达式替换字符串

c# - IntPtr 算法

c# - 如何以编程方式在 Stackdriver 中将 NLog 与 JsonPayload 结合使用

c# - 我的 MVC3 razor View 中的 if 语句存在问题

c# - if else with razor 简写

c# - 获取参数对象的属性

javascript - 结合 JavaScript 和 ASP.NET MVC HTML 代码问题

asp.net-mvc - ASP.NET MVC 中无法访问服务器变量

c# - C# 中原始类型的容器是使用值语义还是指针/引用语义?