I am new to ASP.NET MVC and have been struggling to find a solution to this problem. Despite searching on various platforms, including Stack Overflow, I have not been able to resolve it. Here are some links to solutions that did not work for me:
Possible to access MVC ViewBag object from Javascript file?
MVC 3 - Assign ViewBag Contents to Javascript string
Below is the ajax call I am making to the server:
var xhr = new XMLHttpRequest();
xhr.open('POST', '/Prize/UploadPassport');
xhr.send(formdata);
xhr.onreadystatechange = function () {
if (xhr.readyState == 4 && xhr.status == 200) {
var data = JSON.parse(xhr.responseText)
if (data.nationality != "") {
$('#PassportData tbody').append('<tr><td data-title="@Web.Resources.MyResources.PassportNationality">' + data.nationality + '</td><td data-title="@Web.Resources.MyResources.PassportName">' + data.passportName + '</td><td><a><i id="viewApp_' + data.passportID + '" class="fa fa-search fa-lg" onclick="ViewPassport(' + data.passportID + ');"> <iframe id="img_' + data.passportID + '" class="costumeiframe"></iframe></i></a></td></tr>');
}
else {
//var errorMsg = data.errorMsg;
ShowDataValidationMessage("@ViewBag.FileError"); //here i'm getting an empty string
}
}
}
In my server-side action, I set ViewBag.FileError based on certain conditions as shown below:
public ActionResult UploadPassport(HttpPostedFileBase FileUpload, string PassportCopyNationality)
{
if (Condition)
{
//Database access
}
else
{
if (isFileAlreadyExist)
{
ViewBag.FileError = Web.Resources.MyResources.PassportAttachmentValidationForFile;
}
else if (file.ContentLength > 3145728 || !isFileTypeLegal)
{
ViewBag.FileError = Web.Resources.MyResources.FileError;
}
return Json(new { nationality = "", passportName = "", passportID = "" });
}
}
catch (IOException io)
{
return Json("File not uploaded");
}
}
The issue I am facing is receiving an empty string.