上传的图片在“编辑”视图上引发空异常

时间:2018-12-24 14:00:28

标签: asp.net-mvc

显示或编辑添加到我的视图中的图像时出现问题。该图像将不会显示在我的详细信息视图中,并且如果我尝试上传新图像,则会收到null异常。

这是我的课程:

 public class PreConference
  {
    [Key]
    public int ConferenceID { get; set; }
    public string Title { get; set; }
    public string Description { get; set; }

    [DisplayName("Start Date")]
    [DataType(DataType.Date)]
    [DisplayFormat(DataFormatString = "{0:yyyy-MM-dd}", 
    ApplyFormatInEditMode = true)]
    public DateTime? StartDate { get; set; }

    [DataType(DataType.Date)]
    [DisplayFormat(DataFormatString = "{0:dd MMM yyyy}")]
    public DateTime? EndDate { get; set; }

    [DataType(DataType.Time)]
    [DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = " 
    {0:hh\\:mm}")]
    public TimeSpan? StartTime { get; set; }

    [DataType(DataType.Time)]
    [DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = " 
   {0:hh\\:mm}")]
    public TimeSpan? EndTime { get; set; }

    public virtual List<FileUsed> Files { get; set; }
    public virtual ICollection<FilePath> FilePaths { get; set; }      
    public virtual ICollection<User> users { get; set; }
  }


public class FileUsed
  {
    [Key]
    public int FileId { get; set; }
    [StringLength(255)]
    public string FileName { get; set; }
    [StringLength(100)]
    public string ContentType { get; set; }
    public byte[] Content { get; set; }
    public FileTypes FileType { get; set; }
    public int? eventID { get; set; }
    public int? UserID { get; set; }
    public int? PaperID { get; set; }
    public int? ConferenceID { get; set; }


    public User users { get; set; }

    public Paper papers { get; set; }

    public EventClass eventClasses { get; set; }

    public PreConference conferences { get; set; }


   }

   public enum FileTypes
  {
    Avatar = 1,
    Photo = 2
  }

这是我的控制器:

public class PreConferencesController : Controller
{
    private BattconDBContext db = new BattconDBContext();

    // GET: PreConferences
    public ActionResult Index()
    {
        return View(db.preconference_tbl.Include(s =>s.Files).ToList());
    }

    // GET: PreConferences/Details/5
    public ActionResult Details(int? id)
    {
        if (id == null)
        {
            return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
        }

        PreConference preConference = db.preconference_tbl.Include(s => s.Files).SingleOrDefault(s => s.ConferenceID == id);

        if (preConference == null)
        {
            return HttpNotFound();
        }
        return View(preConference);
    }

    // GET: PreConferences/Create
    public ActionResult Create()
    {
        return View();
    }

    // POST: PreConferences/Create
    // To protect from overposting attacks, please enable the specific properties you want to bind to, for 
    // more details see https://go.microsoft.com/fwlink/?LinkId=317598.
    [HttpPost]
    [ValidateAntiForgeryToken]
    public ActionResult Create([Bind(Include = "ConferenceID,Title,Description,StartDate,EndDate,StartTime,EndTime")] PreConference preConference, HttpPostedFileBase upload)
    {
        try
        {
            if (ModelState.IsValid)
            {
                if (upload != null && upload.ContentLength > 0)
                {
                    var avatar = new FileUsed
                    {
                        FileName = System.IO.Path.GetFileName(upload.FileName),
                        FileType = FileTypes.Avatar,
                        ContentType = upload.ContentType
                    };
                    using (var reader = new System.IO.BinaryReader(upload.InputStream))
                    {
                        avatar.Content = reader.ReadBytes(upload.ContentLength);
                    }
                    preConference.Files = new List<FileUsed> { avatar };
                }
                db.preconference_tbl.Add(preConference);
                db.SaveChanges();
                return RedirectToAction("Index");
            }
        }
        catch (RetryLimitExceededException /* dex */)
        {
            //Log the error (uncomment dex variable name and add a line here to write a log.
            ModelState.AddModelError("", "Unable to save changes. Try again, and if the problem persists see your system administrator.");
        }
        return View(preConference);

    }

    // GET: PreConferences/Edit/5
    public ActionResult Edit(int? id)
    {
        if (id == null)
        {
            return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
        }
        PreConference preConference = db.preconference_tbl.Include(s => s.Files).SingleOrDefault(s => s.ConferenceID == id);
        if (preConference == null)
        {
            return HttpNotFound();
        }
        return View(preConference);
    }

    // POST: PreConferences/Edit/5
    // To protect from overposting attacks, please enable the specific properties you want to bind to, for 
    // more details see https://go.microsoft.com/fwlink/?LinkId=317598.
    [HttpPost]
    [ValidateAntiForgeryToken]
    public ActionResult Edit(int? id, HttpPostedFileBase upload)
    {
        if (id == null)
        {
            return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
        }
        var conferenceToUpdate = db.preconference_tbl.Find(id);
        if (TryUpdateModel(conferenceToUpdate, "",
            new string[] { "ConferenceID","Title","Description","StartDate","EndDate","StartTime","EndTime" }))
        {
            try
            {
                if (upload != null && upload.ContentLength > 0)
                {
                    if (conferenceToUpdate.Files.Any(f => f.FileType == FileTypes.Avatar))
                    {
                        db.files_tbl.Remove(conferenceToUpdate.Files.First(f => f.FileType == FileTypes.Avatar));
                    }
                    var avatar = new FileUsed
                    {
                        FileName = System.IO.Path.GetFileName(upload.FileName),
                        FileType = FileTypes.Avatar,
                        ContentType = upload.ContentType
                    };
                    using (var reader = new System.IO.BinaryReader(upload.InputStream))
                    {
                        avatar.Content = reader.ReadBytes(upload.ContentLength);
                    }
                    conferenceToUpdate.Files = new List<FileUsed> { avatar };
                }
                db.Entry(conferenceToUpdate).State = EntityState.Modified;
                db.SaveChanges();

                return RedirectToAction("Index");
            }
            catch (RetryLimitExceededException /* dex */)
            {
                //Log the error (uncomment dex variable name and add a line 
                 here to write a log.
                ModelState.AddModelError("", "Unable to save changes. Try 
                again, and if the problem persists, see your system 
                administrator.");
            }
        }
        return View(conferenceToUpdate);
    }

    // GET: PreConferences/Delete/5
    public ActionResult Delete(int? id)
    {
        if (id == null)
        {
            return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
        }
        PreConference preConference = db.preconference_tbl.Include(s => 
        s.Files).SingleOrDefault(s => s.ConferenceID == id);
        if (preConference == null)
        {
            return HttpNotFound();
        }
        return View(preConference);
    }

    // POST: PreConferences/Delete/5
    [HttpPost, ActionName("Delete")]
    [ValidateAntiForgeryToken]
    public ActionResult DeleteConfirmed(int id)
    {
        PreConference preConference = db.preconference_tbl.Include(s => 
        s.Files).SingleOrDefault(s => s.ConferenceID == id);
        db.preconference_tbl.Remove(preConference);
        db.SaveChanges();
        return RedirectToAction("Index");
    }

    protected override void Dispose(bool disposing)
    {
        if (disposing)
        {
            db.Dispose();
        }
        base.Dispose(disposing);
    }
    }

这是我的修改视图:

@model BattconEvent.Models.PreConference

  @{
    ViewBag.Title = "Edit";
    Layout = "~/Views/Shared/_Layout.cshtml";
   }

<h2>Edit</h2>


@using (Html.BeginForm("Edit", "PreConferences", null, FormMethod.Post, new 
{ enctype = "multipart/form-data" }))
{
@Html.AntiForgeryToken()

<div class="form-horizontal">
<h4>PreConference</h4>
<hr />
@Html.ValidationSummary(true, "", new { @class = "text-danger" })
@Html.HiddenFor(model => model.ConferenceID)

<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.Description, htmlAttributes: new { @class = "control-label col-md-2" })
    <div class="col-md-10">
        @Html.EditorFor(model => model.Description, new { htmlAttributes = new { @class = "form-control" } })
        @Html.ValidationMessageFor(model => model.Description, "", new { @class = "text-danger" })
    </div>
</div>

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

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

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

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

@if (Model.Files.Any(f => f.FileType == FileTypes.Avatar))
{
    <div class="form-group">
        <span class="control-label col-md-2"><strong>Current Avatar</strong></span>
        <div class="col-md-10">
            <img src="~/Images?id=@Model.Files.First(f => f.FileType == FileTypes.Avatar).FileId" alt="avatar" />
        </div>
    </div>
}

<div class="form-group">
    @Html.Label("Avatar", new { @class = "control-label col-md-2" })
    <div class="col-md-10">
        <input type="file" id="Avatar" name="upload" />
    </div>
</div>


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

这是我的详细信息视图:

  @model BattconEvent.Models.PreConference

    @{
        ViewBag.Title = "Details";
        Layout = "~/Views/Shared/_Layout.cshtml";
      }

 <h2>Details</h2>

<div>
<h4>PreConference</h4>
<hr />
<dl class="dl-horizontal">
    @if (Model.Files.Any(f => f.FileType == FileTypes.Avatar))
    {
        <dt>
            Avatar
        </dt>
        <dd>
            <img src="~/Images/?id=@Model.Files.First(f => f.FileType == FileTypes.Avatar).FileId" alt="avatar" />
        </dd>
    }
    <dt>
        @Html.DisplayNameFor(model => model.Title)
    </dt>

    <dd>
        @Html.DisplayFor(model => model.Title)
    </dd>

    <dt>
        @Html.DisplayNameFor(model => model.Description)
    </dt>

    <dd>
        @Html.DisplayFor(model => model.Description)
    </dd>

    <dt>
        @Html.DisplayNameFor(model => model.StartDate)
    </dt>

    <dd>
        @Html.DisplayFor(model => model.StartDate)
    </dd>

    <dt>
        @Html.DisplayNameFor(model => model.EndDate)
    </dt>

    <dd>
        @Html.DisplayFor(model => model.EndDate)
    </dd>

    <dt>
        @Html.DisplayNameFor(model => model.StartTime)
    </dt>

    <dd>
        @Html.DisplayFor(model => model.StartTime)
    </dd>

    <dt>
        @Html.DisplayNameFor(model => model.EndTime)
    </dt>

    <dd>
        @Html.DisplayFor(model => model.EndTime)
    </dd>

    </dl>
  </div>
  <p>
@Html.ActionLink("Edit", "Edit", new { id = Model.ConferenceID }) |
@Html.ActionLink("Back to List", "Index")
</p>

我不知道为什么它不显示或为什么引发错误。请帮助

0 个答案:

没有答案