There are similar posts out there but they do not seem to represent my situation. Apologies in advance if this is a re-post.
I have my view as
#FileUpload.GetHtml(initialNumberOfFiles:1,allowMoreFilesToBeAdded:true,includeFormTag:true, uploadText: "Upload" )
#model IEnumerable<EpubsLibrary.Models.Partner>
#{ using (Html.BeginForm("Index","Epub"))
{
#Html.DropDownList("PartnerID", (IEnumerable<SelectListItem>)ViewBag.Partners, "None")
<input type="submit" value="send" id="pickPartner" hidden="hidden"/>
}
}
<script type="text/javascript">
$(".file-upload-buttons input").click(function () {
$("#pickPartner").click();
});
</script>
my controller is
[HttpPost]
public ActionResult Index(IEnumerable<HttpPostedFileBase> fileUpload, FormCollection collection)
{
int selectedPartner, count =0;
//int selectedPartner = int.Parse(collection["PartnerID"]);
if(!int.TryParse(collection["PartnerID"], out selectedPartner))
{
selectedPartner = 0;
ModelState.AddModelError("", "You must pick a publishing agency");
}
IList<Partner> p = r.ListPartners();
ViewBag.Partners = new SelectList(p.AsEnumerable(), "PartnerID", "Name", selectedPartner);
//make sure files were selected for upload
if (fileUpload != null)
{
for (int i = 0; i < fileUpload.Count(); i++)
{
//make sure every file selected != null
if (fileUpload.ElementAt(i) != null)
{
count++;
var file = fileUpload.ElementAt(i);
if (file.ContentLength > 0)
{
var fileName = Path.GetFileName(file.FileName);
// need to modify this for saving the files to the server
var path = Path.Combine(Server.MapPath("/App_Data/uploads"), Guid.NewGuid() + "-" + fileName);
file.SaveAs(path);
}
}
}
}
if (count == 0)
{
ModelState.AddModelError("", "You must upload at least one file!");
}
return View();
}
I am using the file upload helper from Microsoft Web Helpers to upload files. The problem I am having is the helper created a form and I have another form I need to submit data from as well on the same page.
I thought I could link the submit buttons so that when you click upload it also sent the other form data but the data is not being sent. Each form works independently of the other with no issue but I need them to work together. Any advice would be appreciated.
Ok I updated the view with
#model IEnumerable<EpubsLibrary.Models.Partner>
#{ using (Html.BeginForm("Index","Epub"))
{
#Html.DropDownList("PartnerID", (IEnumerable<SelectListItem>)ViewBag.Partners, "None")
#FileUpload.GetHtml(initialNumberOfFiles: 1, allowMoreFilesToBeAdded: true, includeFormTag: false, uploadText: "Upload")
<input type="submit" value="send" id="pickPartner"/>
}
}
But now the file data does not seem to be getting passed anymore.
-- Update --
I have made the following changes.
The view now looks like
#model IEnumerable<EpubsLibrary.Models.Partner>
#{ using (Html.BeginForm("Index", "Epub", new { enctype = "multipart/form-data" }))
{
#Html.DropDownList("PartnerID", (IEnumerable<SelectListItem>)ViewBag.Partners, "None")
#FileUpload.GetHtml(initialNumberOfFiles: 1, allowMoreFilesToBeAdded: true, includeFormTag: false, uploadText: "Upload")
<input type="submit" value="send" id="pickPartner"/>
}
}
and the controller
[HttpPost]
public ActionResult Index(IEnumerable<HttpPostedFileBase> fileUpload, int PartnerID = 0)
//public ActionResult Index(IEnumerable<HttpPostedFileBase> fileUpload, FormCollection collection)
{
int count =0;
IList<Partner> p = r.ListPartners();
ViewBag.Partners = new SelectList(p.AsEnumerable(), "PartnerID", "Name", PartnerID);
//make sure files were selected for upload
if (fileUpload != null)
{
for (int i = 0; i < fileUpload.Count(); i++)
{
//make sure every file selected != null
if (fileUpload.ElementAt(i) != null)
{
count++;
var file = fileUpload.ElementAt(i);
if (file.ContentLength > 0)
{
var fileName = Path.GetFileName(file.FileName);
// need to modify this for saving the files to the server
var path = Path.Combine(Server.MapPath("/App_Data/uploads"), Guid.NewGuid() + "-" + fileName);
file.SaveAs(path);
}
}
}
}
if (count == 0)
{
ModelState.AddModelError("", "You must upload at least one file!");
}
return View();
}
}
I am trying to figure out how the file data is getting sent over in the post (if it is) so I can save the files.
-- Final Update with Answer --
Well the problem turned out to be two fold.. 1st the issue with #FileUpload and needing to set includeFormTag: false
The other problem I discovered was I needed to make sure in my #Html.BeginForm I included FormMethod.Post This was discovered when the fileUpload count kept coming back as 0. I ran the profiler on firebug and it pointed out that the file data was not actually getting posted. Here is the corrected code below.
my view
#model IEnumerable<EpubsLibrary.Models.Partner>
#{ using (Html.BeginForm("Index", "Epub", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
#Html.DropDownList("PartnerID", (IEnumerable<SelectListItem>)ViewBag.Partners, "None")
#FileUpload.GetHtml(initialNumberOfFiles: 1, allowMoreFilesToBeAdded: true, includeFormTag: false, uploadText: "Upload")
<input type="submit" value="send" id="pickPartner"/>
}
}
my controller
[HttpPost]
public ActionResult Index(IEnumerable<HttpPostedFileBase> fileUpload, int PartnerID = 0)
{
int count =0;
IList<Partner> p = r.ListPartners();
ViewBag.Partners = new SelectList(p.AsEnumerable(), "PartnerID", "Name", PartnerID);
//make sure files were selected for upload
if (fileUpload != null)
{
for (int i = 0; i < fileUpload.Count(); i++)
{
//make sure every file selected != null
if (fileUpload.ElementAt(i) != null)
{
count++;
var file = fileUpload.ElementAt(i);
if (file.ContentLength > 0)
{
var fileName = Path.GetFileName(file.FileName);
// need to modify this for saving the files to the server
var path = Path.Combine(Server.MapPath("/App_Data/uploads"), Guid.NewGuid() + "-" + fileName);
file.SaveAs(path);
}
}
}
}
if (count == 0)
{
ModelState.AddModelError("", "You must upload at least one file!");
}
return View();
}
Thank you #Jay and #Vasile Bujac for your help with this.
Set IncludeFormTag to false and put it inside your other form using.
#model IEnumerable<EpubsLibrary.Models.Partner>
#{ using (Html.BeginForm("Index","Epub"))
{
#FileUpload.GetHtml(initialNumberOfFiles:1,allowMoreFilesToBeAdded:true,includeFormTag:false, uploadText: "Upload" )
#Html.DropDownList("PartnerID", (IEnumerable<SelectListItem>)ViewBag.Partners, "None")
<input type="submit" value="send" id="pickPartner" hidden="hidden"/>
}
}
Update:
Try changing the signature of your view to this:
public ActionResult Index(IEnumerable<HttpPostedFileBase> fileUpload, int PartnerID = 0)
Check the overloads for FileUpload.GetHtml and see if there is a parameter to set the field name for your file uploads. Previously it was just the files being uploaded, now its files and a parameter, so naming becomes more important.
You should use the same form for dropdownlist and file inputs. You can do this by putting the FileUpload helper inside the form, and setting "includeFormTag" parameter to false.
#model IEnumerable<EpubsLibrary.Models.Partner>
#using (Html.BeginForm("Index","Epub")) {
#FileUpload.GetHtml(initialNumberOfFiles:1,allowMoreFilesToBeAdded:true,includeFormTag:false, uploadText: "Upload" )
#Html.DropDownList("PartnerID", (IEnumerable<SelectListItem>)ViewBag.Partners, "None")
<input type="submit" value="send" id="pickPartner" hidden="hidden"/>
}
Related
I have created an Image Slider using jQuery, but it doesn't work at random moments. After reloading the page I get the following error:
Uncaught TypeError: Cannot read property 'indexOf' of undefined
at i.fn.init.i.fn.load (jquery?v=eJAcMfrInnLuvmR6YmGFt2ky0cO2ssn2OaxtB6iWFKQ1:1)
at HTMLImageElement.<anonymous> (slider?v=iXGFgGvKoKTyJMnF1faQOZMvYM6od0eK7irNUQ3FiMg1:1)
at Function.each (jquery?v=eJAcMfrInnLuvmR6YmGFt2ky0cO2ssn2OaxtB6iWFKQ1:1)
at i.fn.init.each (jquery?v=eJAcMfrInnLuvmR6YmGFt2ky0cO2ssn2OaxtB6iWFKQ1:1)
at HTMLImageElement.<anonymous> (slider?v=iXGFgGvKoKTyJMnF1faQOZMvYM6od0eK7irNUQ3FiMg1:1)
at Function.each (jquery?v=eJAcMfrInnLuvmR6YmGFt2ky0cO2ssn2OaxtB6iWFKQ1:1)
at i.fn.init.each (jquery?v=eJAcMfrInnLuvmR6YmGFt2ky0cO2ssn2OaxtB6iWFKQ1:1)
at et (slider?v=iXGFgGvKoKTyJMnF1faQOZMvYM6od0eK7irNUQ3FiMg1:1)
at ft (slider?v=iXGFgGvKoKTyJMnF1faQOZMvYM6od0eK7irNUQ3FiMg1:1)
at k (slider?v=iXGFgGvKoKTyJMnF1faQOZMvYM6od0eK7irNUQ3FiMg1:1)
Controller:
public class SliderController : Controller
{
// GET: Slider
public ActionResult Index()
{
using (BasDbContext db = new BasDbContext())
{
return View(db.gallery.ToList());
}
//return View();
}
//Add Images in slider
public ActionResult AddImage()
{
return View();
}
[HttpPost]
public ActionResult AddImage(HttpPostedFileBase ImagePath)
{
if (ImagePath != null)
{
// You can skip this block, because it is only to force the user to upload specific resolution pics
//System.Drawing.Image img = System.Drawing.Image.FromStream(ImagePath.InputStream);
//if ((img.Width != 800) || (img.Height != 356))
//{
// ModelState.AddModelError("", "Image resolution must be 800 x 356 pixels");
// return View();
//}
// Upload your pic
string pic = System.IO.Path.GetFileName(ImagePath.FileName);
string path = System.IO.Path.Combine(Server.MapPath(#"\cdm\Content\images\"), pic);
ImagePath.SaveAs(path);
using (BasDbContext db = new BasDbContext())
{
Gallery gallery = new Gallery { ImagePath = #"\cdm\Content\images\" + pic };
db.gallery.Add(gallery);
db.gallery.Add(gallery).DateAdded = gallery.DateAdded = DateTime.Now;
db.SaveChanges();
}
}
return RedirectToAction("Index");
}
// Delete Multiple Images
public ActionResult DeleteImages()
{
using (BasDbContext db = new BasDbContext())
{
return View(db.gallery.ToList());
}
}
[HttpPost]
public ActionResult DeleteImages(IEnumerable<int> ImagesIDs)
{
using (BasDbContext db = new BasDbContext())
{
try
{
foreach (var id in ImagesIDs)
{
var image = db.gallery.Single(s => s.ID == id);
string imgPath = Server.MapPath(image.ImagePath);
db.gallery.Remove(image);
if (System.IO.File.Exists(imgPath))
System.IO.File.Delete(imgPath);
}
db.SaveChanges();
}
catch
{
TempData["AlertMessage"] = "Something went wrong, try again";
}
}
return RedirectToAction("DeleteImages");
}
}
}
Index:
#model IEnumerable<ConcremoteDeviceManagment.Models.Gallery>
#{
ViewBag.Title = "Index";
//Layout = "~/Views/Shared/_Layout.cshtml";
}
#if (TempData["AlertMessage"] != null)
{
<p class="alert alert-danger" id="successMessage">#TempData["AlertMessage"]</p>
}
<h2>Index</h2>
<p>
<button onclick="location.href='#Url.Action("AddImage", "Slider")';return false; " class="btn btn-primary">Add Image</button>
<button onclick="location.href='#Url.Action("DeleteImages", "Slider")';return false; " class="btn btn-danger">Delete Image</button>
</p>
#Html.Partial("~/Views/Shared/SliderPartial.cshtml", Model)
SliderPartial:
<div class="bxslider">
#foreach (var image in Model)
{
<div><img src="#Url.Content(image.ImagePath)" /></div>
}
</div>
<script>
$(document).ready(function () {
$('.bxslider').bxSlider({
mode: 'fade',
captions: true,
slideWidth: 600
});
});
</script>
I think something is going wrong in SliderPartial.
Controller and Index seems to be fine.
I hope somebody is able to help me out.
More information will be given when needed
I'm following this example on the MS website for File Uploads using Razor and C#.
If I have more than one File upload buttons, how would the C# code know which button the uploaded file is from? Based on the button the file was uploaded from, I will be saving files to specific folders.
https://learn.microsoft.com/en-us/aspnet/web-pages/overview/data/working-with-files
#using Microsoft.Web.Helpers;
#{
var fileName = "";
if (IsPost) {
var fileSavePath = "";
var uploadedFile = Request.Files[0];
fileName = Path.GetFileName(uploadedFile.FileName);
fileSavePath = Server.MapPath("~/App_Data/UploadedFiles/" +
fileName);
uploadedFile.SaveAs(fileSavePath);
}
}
<!DOCTYPE html>
<html>
<head>
<title>FileUpload - Single-File Example</title>
</head>
<body>
<h1>FileUpload - Single-File Example</h1>
#FileUpload.GetHtml(
initialNumberOfFiles:1,
allowMoreFilesToBeAdded:false,
includeFormTag:true,
uploadText:"Upload")
#if (IsPost) {
<span>File uploaded!</span><br/>
}
</body>
</html>
The way to do this is to name the buttons the same, but give them different values. You can then do a case statement and direct the logic based on the value.
Razor
#using (Html.BeginForm("Index", "Home", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
<input type="file" name="FirstUpload" />
<input type="submit" name="submitID" id="submitID" value="Upload1" />
<input type="file" name="SecondUpload" />
<input type="submit" name="submitID" id="submitID" value="Upload2" />
}
Controller
public ActionResult Index()
{
return View();
}
[HttpPost]
public ActionResult Index(FormCollection collection)
{
string btn = Request.Params["submitID"];
switch (btn)
{
case "Upload1":
for (int i = 0; i < Request.Files.Count; i++)
{
var file = Request.Files[i];
}
break;
case "Upload2":
for (int i = 0; i < Request.Files.Count; i++)
{
var file = Request.Files[i];
}
break;
}
return View();
}
I had a similar problem and ended up with following code:
Razor
//BeginForm and other staff
#foreach (var d in Model.Types)
{
<input type="file" name="doc:#d.Id:upload" />//#d.Id is the key point
<button formenctype="multipart/form-data"
type="submit" formaction="/MyController/uploaddoc"
name="typeid" formmethod="post" value="#d.Id">//this way I send Id to controller
Upload
</button>
}
MyController
[HttpPost]
[ValidateAntiForgeryToken]
[Route("mycontroller/uploaddoc")]//same as formaction
public async Task<ActionResult> UploadDoc(FormCollection data, int typeid)
{
//restore inpput name
var fl = Request.Files["doc:" + typeid.ToString() + ":upload"];
if (fl != null && fl.ContentLength > 0)
{
var path = Server.MapPath("~/app_data/docs");
var fn = Guid.NewGuid().ToString();//random name
using (FileStream fs = System.IO.File.Create(Path.Combine(path, fn)))
{
await fl.InputStream.CopyToAsync(fs);
}
}
}
I'm currently working on a project where the previous contractor had an attachments area within our site. The piece works for the most part but has issues when redirecting back after uploading the file, plus I don't like the fact the page does a full page reload just to update a grid to show the uploaded file.
My goal is to instead do an Ajax call for the upload versus form submit. I have added this in, however, the return forces a download of the Json object (using IE 11). I have researched how to get around this and have yet to find any substantial ways around it.
Is it possible to upload a file using Ajax and not send back a download of the Json object?
Below is my code.
View (Upload.cshtml)
#using (Html.BeginForm("Upload", "PM", FormMethod.Post, new { enctype = "multipart/form-data", id = "frmUpload" }))
{
#Html.ValidationSummary(true)
<table>
...
<tr>
<td>#Html.Label("File: ")</td>
<td>
<input type="file" name="file" id="file"/>
#Html.ValidationMessage("file","File is required")
</td>
</tr>
...
<tr>
<td colspan="2">
<p>
<button type="submit" class="t-button" id="btnSubmit">
Attach</button>
<button type="button" class="t-button" onclick="CloseAttachmentWindow()">
Cancel</button>
</p>
</td>
</tr>
</table>
}
<script type="text/javascript">
$(document).ready(function () {
$("#btnSubmit").click(function (e) {
e.preventDefault();
if (!$('form').valid())
return false;
//Upload document
$.ajax({
type: "POST",
cache: false,
url: "/PM/Upload",
dataType: "json",
contentType: false,
processData: false,
data: $('form').serialize(),
success: function (result) {
if (result.success) {
var window = $("#error").data("tWindow");
window.content("<b>Attachment successfully added</b>").title("Success!");
window.center().open();
CloseAttachmentWindow();
}
else {
var window = $("#error").data("tWindow");
window.content("<b>Error: Unable to Upload Document. Please try again. "
+ "If this fails, contact the administrators with the below details.</b>"
+ '\n' + '\n' + result.Error).title("Error");
window.center().open();
}
},
error: function (xhtr, e, e2) {
var window = $("#error").data("tWindow");
window.content(e + '\n' + xhtr.responseText, 'error', '');
window.center().open();
}
});
});
});
</script>
PMController.cs
[HttpPost]
public ActionResult Upload(HttpPostedFileBase file, FormCollection formcollection)
{
if (file != null)
{
var cntPOC = int.Parse(Session["cntPOC"].ToString());
try
{
var cntFileType = _fileTypeRepo.GetCntFileTypeByMimeType(file.ContentType);
if (cntFileType == 0)
throw new Exception("This file type is not supported");
var strAttachmentName = formcollection["AttachmentName"];
var strAttachmentType = formcollection["AttachmentType"];
var length = file.ContentLength;
var tmpFile = new byte[length];
if (tmpFile.Count() > 0)
{
file.InputStream.Read(tmpFile, 0, length);
var intAttchmentId = _AttachRepo.GetNextAttachmentId() + 1;
var objAttachment = new TBLATTACHMENT
{
CNTATTACHMENT = intAttchmentId,
CNTPOC = cntPOC,
CNTFILETYPE = cntFileType,
CNTATTACHMENTTYPE = Convert.ToDecimal(strAttachmentType),
DTMCREATED = DateTime.Now,
STRATTACHMENTTITLE = strAttachmentName,
BLBATTACHMENT = tmpFile,
STRORIGINALFILENAME = file.FileName,
YSNDELETED = 0
};
_AttachRepo.Add(objAttachment);
_AttachRepo.Save();
return Json(new { success = true, Error = "" });
}
//File not real
else
return Json(new { success = false, Error = "Please select appropriate file" });
}
catch (Exception ex)
{
logger.LogError("File Upload", ex);
if (ex.InnerException != null)
ModelState.AddModelError("Error", ex.InnerException.ToString());
else
ModelState.AddModelError("Error", ex.Message.ToString());
TempData["ModelState"] = ModelState;
return Json(new { success = false, Error = ex.Message });
}
}
else
{
logger.LogError("File Upload Error. File was not selected");
ModelState.AddModelError("Error", "Please select file");
TempData["ModelState"] = ModelState;
return Json(new { success = false, Error = "File was not selected" });
}
}
As is, using this code, I can upload documents, however, I get the prompt to download the Json object upon return.
NOTE Long story short, you cannot do this. I had to learn the hard way and never did find a solution. I did find a way to do it for downloads, but not uploads.
Options:
Remove change the button type submit to button <input type="button"/>
<input type="submit" onclick="return false">
return false; or add event handlers
$("input[type='submit']").click(function() { return false; });
or
$("form").submit(function() { return false; });
<form onsubmit="return false"> ...</form>
in order to avoid refresh at all "buttons", even with onclick assigned.
changing the submit type to button is the optimal one.
Hi to all of you I am facing a problem on uploading a file and saving it into a folder here is my view
<div class="admin-empty-dashboard">
#using (Html.BeginForm("UploadResumes", "Employee", new { enctype = "multipart/form-data" }))
{
#Html.AntiForgeryToken()
#Html.ValidationSummary(true)
<div class="icon">
<i class="ion-ios-book-outline"></i>
</div>
<h4>Welcome #Model.FullName!</h4>
<p>#ViewBag.Error</p>
<div class="form-group bootstrap-fileinput-style-01">
<label>Upload Resume</label>
<input type="file" name="file" required="required" class="btn btn-primary" style="margin-left:265px" accept="application/msword,text/plain, application/pdf">
<span class="font12 font-italic">** File must not bigger than 2MB</span>
</div>
<input type="submit" name="name" class="btn btn-primary" value="UploadResumes" />
}
</div>
and here is my controllers action problem is that it HttpPostedFileBase object value is always null and i ran Request.Files.Count it's also giving me zero where is problem?
public ActionResult UploadResumes(HttpPostedFileBase file)
{
if (Session["UserID"] != null && Session["UserName"] != null && Session["EmployeeID"] != null)
{
int id = Convert.ToInt32(Session["EmployeeID"]);
string[] allowedExtenssions = new string[] { ".pdf", ".doc", ".docx" };
string cvPath = "~/cvs/Employee_cvs/";
if (!Directory.Exists(Server.MapPath(cvPath)))
Directory.CreateDirectory(Server.MapPath(cvPath));
MyDbContext db=new MyDbContext();
tblEmployee employee = (from s in db.tblEmployees where s.UserId == id select s).FirstOrDefault();
// HttpPostedFileBase cv = Request.Files["CV"];
if (file != null)
{
if (file.ContentLength > 0)
{
string ext = Path.GetExtension(file.FileName);
if (allowedExtenssions.Contains(ext.ToLower()))
{
string fileName = DateTime.Now.Ticks + ext;
string filePath = cvPath + fileName;
string serverPath = Server.MapPath(filePath);
file.SaveAs(serverPath);
employee.cvUrl = filePath;
}
}
ViewBag.Error = "Some Error Occured";
}
return RedirectToAction("Dashboard");
}
else
{
return RedirectToAction("Login", "User");
}
}
Update like below and check
#using (Html.BeginForm("UploadResumes", "Employee",FormMethod.Post, new { enctype = "multipart/form-data" }))
{
}
Also
[HttpPost]
public ActionResult UploadResumes(HttpPostedFileBase file)
{
}
Try changing your parameters on your controller to
public ActionResult UploadResumes(Model yourModel, HttpHostedFileBase file)
In most of my controllers that require a file for upload, are usually array based. Make you function parameters an array like this:
public ActionResult UploadResumes(HttpPostedFileBase[] files){
}
Here is the code for my view and controller
#using (Html.BeginForm("PdfHeaderAndFooterManager", "Dashboard", FormMethod.Post, new { enctype = "multipart/form-data", id = "formPdfImages" }))
div id="resultMessage"></div>
}
CONTROLLER ACTION
public ActionResult PdfHeaderAndFooterManager(HttpPostedFileBase headerImage, HttpPostedFileBase footerImage)
{
//some code to declare variables
if (headerImage != null)
{
if (!String.IsNullOrEmpty(headerImage.ContentType))
{
headerImageContentType = imageHelper.IsValidImageType(headerImage.ContentType);
if (headerImageContentType)
{
resizedHeaderImage = imageHelper.ResizeImage(headerImage.InputStream);
}
else
{
return Json(new { success = false, message = "Please Upload an image* file less than 2GB." });
}
}
}
if (footerImage != null)
{
if (!String.IsNullOrEmpty(footerImage.ContentType))
{
footerImageContentType = imageHelper.IsValidImageType(footerImage.ContentType);
if (footerImageContentType)
{
resizedFooterImage = imageHelper.ResizeImage(footerImage.InputStream);
}
else
{
return Json(new { success = false, message = "Please Upload an image* file less than 2GB." });
}
}
}
if (P24DataPrincipal.CurrentIdentity != null)
{
if (resizedHeaderImage != null || resizedFooterImage != null)
{
//add to DB code
return Json(new { success = true, message = "Image(s) Uploaded Successfully." });
}
else
{
return Json(new {success = false, message = "Upload atleast 1 image file." });
}
}
return View("someview");
}
Can someone please assist me on how would have to write a jquery function to just display the Json results returned in the action above in my view. THANKS
EDITORIAL NOTE
It would appear that you want to send back JSON OR an Image. You can probably do some interesting things with the HTML 5 Blob API (or sending the image back as a JSON payload with a DATA URI). In general, there is no simple solution to this, especially via AJAX.
END NOTE
Assuming jQuery 1.5 or better:
jQuery.post('/TheController/PdfHeaderAndFooterManager')
.success(function(d){
jQuery('#resultMessage').html(d.message).attr('data-action-success',d.success);
}).error(function(){
jQuery('#resultMessage').html('There was an error sending data to the server.').attr('data-action-success', false);
});
And then you can do something fun in CSS like.:
[data-action-success=true]{
color: green;
}
[data-action-success=false]{
color: red;
}
It strikes me that you're returning different types of results. This is fairly uncommon and I would recommend that you split the "Show the form action (a GET action)" and the "Save a form (a POST action)". The GET could return an HTML action result. The POST could always return JSON.
public ActionResult PdfHeaderAndFooterManager(HttpPostedFileBase headerImage, HttpPostedFileBase footerImage)
{
//some code to declare variables
if (headerImage != null)
{
if (!String.IsNullOrEmpty(headerImage.ContentType))
{
headerImageContentType = imageHelper.IsValidImageType(headerImage.ContentType);
if (headerImageContentType)
{
resizedHeaderImage = imageHelper.ResizeImage(headerImage.InputStream);
}
else
{
ViewBag.ResultMessage="<span style='color:red'">Please Upload an image* file less than 2GB.</span>";
return View();
}
}
}
if (footerImage != null)
{
if (!String.IsNullOrEmpty(footerImage.ContentType))
{
footerImageContentType = imageHelper.IsValidImageType(footerImage.ContentType);
if (footerImageContentType)
{
resizedFooterImage = imageHelper.ResizeImage(footerImage.InputStream);
}
else
{
ViewBag.ResultMessage="<span style='color:red'">Please Upload an image* file less than 2GB.</span>";
return View();
}
}
}
if (P24DataPrincipal.CurrentIdentity != null)
{
if (resizedHeaderImage != null || resizedFooterImage != null)
{
//add to DB code
ViewBag.ResultMessage="<span style='color:green'">Image(s) Uploaded Successfully.</span>";
return View();
}
else
{
ViewBag.ResultMessage="<span style='color:red'">Upload atleast 1 image file.</span>";
return View();
}
}
}
And in View,
#using (Html.BeginForm("PdfHeaderAndFooterManager", "Dashboard", FormMethod.Post, new { enctype = "multipart/form-data", id = "formPdfImages" })){
<div id="resultMessage">
#ViewBag.ResultMessage
</div>
}
Try this, hope it will help you.