Shoaib Ahmed

Shoaib Ahmed

  • NA
  • 189
  • 4.9k

Why do I get error while uploading File ?

Jan 23 2019 2:08 AM
This is my View :
@model SimpleUpload.Models.MemberModel
@{
ViewBag.Title = "ContactForm";
}
<h2>ContactForm</h2>
@using (Html.BeginForm("ContactForm", "Home", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
@Html.AntiForgeryToken()
<div class="form-horizontal">
<h4>MemberModel</h4>
<hr />
<div class="form-group">
@Html.LabelFor(model => model.ImageFile, htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.TextBoxFor(m => m.ImageFile, new { type = "file" })
</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>
}
I want to upload the file posted in the form group div.
This my Controller method:
[HttpGet]
public ActionResult ContactForm()
{
return View();
}
[HttpPost]
public ActionResult ContactForm(MemberModel membervalues)
{
//Use Namespace called : System.IO
string FileName = Path.GetFileNameWithoutExtension(membervalues.ImageFile.FileName);
//To Get File Extension
string FileExtension = Path.GetExtension(membervalues.ImageFile.FileName);
//Add Current Date To Attached File Name
FileName = DateTime.Now.ToString("yyyyMMdd") + "-" + FileName.Trim() + FileExtension;
//Get Upload path from Web.Config file AppSettings.
string UploadPath = ConfigurationManager.AppSettings["UserImagePath"].ToString();
//Its Create complete path to store in server.
membervalues.ImagePath = UploadPath + FileName;
//To copy and save file into server.
membervalues.ImageFile.SaveAs(membervalues.ImagePath);
return View();
}
Now, whenever I click on the submit button I find this error 'Object reference not set to an instance of an object.' on the Filename. I cannot figure out where the problem is!
Model class :
public class MemberModel
{
[DisplayName("Upload File")]
public string ImagePath { get; set; }
public HttpPostedFile ImageFile { get; set; }
}
How can I Solve this?

Answers (2)