I have a controller in which I have Create method .My aim is to upload picture along with name and service involved for a particular person.My code is perfectly good.But I'm hitting the error 'Object reference not set to the instance of an object' at the line 'if (leader.File.ContentLength > (2 * 1024 * 1024))' in controller.The code is perfectly good.Please let me know where I'm doing mistake
I have model class like this:
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int ID { get; set; }
[Required(ErrorMessage="The Name is required")]
[MaxLength(20,ErrorMessage="The Maximum characters allowed is 20")]
[MinLength(4,ErrorMessage="The Minimum charcaters allowed is 4")]
public string Name { get; set; }
[Required(ErrorMessage="Picture is required")]
public byte[] Picture { get; set; }
public int ImageSize { get; set; }
[NotMapped]
public HttpPostedFileBase File { get; set; }
public int MinistryID { get; set; }
[ForeignKey("MinistryID")]
public virtual Ministry Ministry { get; set; }
I have Controller class with create method like this:
public ActionResult Create()
{
return View();
}
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create(Leader leader)
{
if (leader.File.ContentLength > (2 * 1024 * 1024))
{
ModelState.AddModelError("CustomError", "File size must be
less than 2 MB");
return View();
}
if (!(leader.File.ContentType == "image/jpeg" ||
leader.File.ContentType == "image/gif"))
{
ModelState.AddModelError("CustomError", "File type allowed :
jpeg and gif");
return View();
}
leader.ImageSize = leader.File.ContentLength;
byte[] data = new byte[leader.File.ContentLength];
leader.File.InputStream.Read(data, 0,
leader.File.ContentLength);
leader.Picture = data;
if(ModelState.IsValid)
{
db.Leaders.Add(leader);
db.SaveChanges();
}
return View(leader);
}
}
The View of the Create method is :
@model ChurchWebsite.Models.Leader
@{
ViewBag.Title = "Create";
Layout = "~/Views/Shared/_Layout.cshtml";
}
<h2>Create</h2>
@using (Html.BeginForm()) {
@Html.AntiForgeryToken()
@Html.ValidationSummary(true)
<fieldset>
<legend>Leader</legend>
<div class="editor-label">
@Html.LabelFor(model => model.Name)
</div>
<div class="editor-field">
@Html.EditorFor(model => model.Name)
@Html.ValidationMessageFor(model => model.Name)
</div>
<div>
@Html.LabelFor(model=>model.Picture)
</div>
<div>
@using (Html.BeginForm("Upload","Image", FormMethod.Post,new{enctype="multipart/form-data"}))
{
@Html.TextBoxFor(Model=> Model.File, new{type="file",enctype="multipart/form-data"})
@Html.ValidationMessage("CustomError")
</div>
<div class="editor-label">
@Html.LabelFor(model => model.MinistryID)
</div>
<div class="editor-field">
@Html.EditorFor(model => model.MinistryID)
@Html.ValidationMessageFor(model => model.MinistryID)
</div>
<p>
<input type="submit" value="Create" />
</p>
</fieldset>
}
@section Scripts {
@Scripts.Render("~/bundles/jqueryval")
}