I am new to razor view engine. I am stuck with a situation where I want to upload an Image with Change event of image browser. Jquery function is given below:
$("#billUpload").change(function (){
$('#uploadImageForm').submit();
}
Razor view code is given below:
@using (Html.BeginForm("Upload", "Home", FormMethod.Post, new { enctype = "multipart/form-data", id = "uploadImageForm" }))
{
<span class="file-input btn btn-sm btn-default btn-file">
Browse…
<input id="billUpload" name="File" type="file">
</span>
}
Controller's code is here:
[HttpPost]
public ActionResult Upload(HttpPostedFileBase file)
{
if (ModelState.IsValid)
{
if (file == null)
{
ModelState.AddModelError("File", "Please Upload Your file");
}
else if (file.ContentLength > 0)
{
int MaxContentLength = 1024 * 1024 * 4; //Size = 4 MB
string[] AllowedFileExtensions = new string[] { ".jpg", ".gif", ".png", ".pdf" };
if (!AllowedFileExtensions.Contains
(file.FileName.Substring(file.FileName.LastIndexOf('.'))))
{
ModelState.AddModelError("File", "Please file of type: " + string.Join(", ", AllowedFileExtensions));
}
else if (file.ContentLength > MaxContentLength)
{
ModelState.AddModelError("File", "Your file is too large, maximum allowed size is: " + MaxContentLength + " MB");
}
else
{
var fileName = Path.GetFileName(file.FileName);
var path = Path.Combine(Server.MapPath("~/Content/images/Bill/"), fileName);
file.SaveAs(path);
ModelState.Clear();
ViewBag.Message = "File uploaded successfully. File path : ~/Content/image/Bill/" + fileName;
}
}
}
return Json("Done",JsonRequestBehavior.AllowGet);
}
Now this entire code runs with no problem for uploading image but I fail to understand how to display this json message return by controller in alert box. Thanks in advance.