Retrieve the string saved in a ViewBag when the ajax call is successful

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.

Answer №1

To start, the @ViewBag.FileError code within your script is razor code that gets processed on the server before being sent to the client. If you don't set ViewBag.FileError = someValue in the GET method that generates the view, it will always be null.

Additionally, since your UploadPassport() method returns a JsonResult and not a view, there is no ViewBag available. To handle this, you can include the value in the JsonResult like so:

return Json(new { fileError = someValue, nationality = "", passportName = "", passportID = "" });

You can then access this value in your script using:

ShowDataValidationMessage("data.fileError");

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

The Safari browser restricts interaction with password inputs but allows interaction with other types of input fields

My password input field is styled like this: <input class="genericButton" id="login-password" type="password" name ="password" placeholder="Password"> While everything functions correctly in Chrome, I encounter an issue with Safari. When I try to i ...

What are the built-in modules in node.js that handle System calls?

Can you list the built-in modules in Node.js that handle system calls, such as child_process? I'm interested in learning about all the methods within these modules. Thank you! ...

Locate a piece of text with jQuery and enclose it within a specified container

Check out this code <form method="get" name="form_delivery"> Pick the country where you want your delivery<br> <select name="deliverymethod"> <option value="0" selected="selected">Choose a country / region</option> ...

I'm having trouble executing the JavaScript function

function contentChange(){ var paragraphs = document.getElementsByTagName("p"); for(var i = 0 ; i < paragraphs.length ; i++){ paragraphs[i].innerHTML = "hello" ;}} contentChange(); I'm struggling to change the content of all ...

React-NextJS encountered an error: TypeError, it cannot read the property 'taste' because it is undefined

Recently, I've been encountering an issue with NextJS that keeps throwing the error message: TypeError: Cannot read property 'taste' of undefined. It's quite frustrating as sometimes it displays the expected output but most of the time ...

The process of exporting and utilizing models in Sequelize

When working on my node.js project with sequelize, I encountered a challenge of exporting and using table models in another file. I typically save table models in a folder, for instance Profile.js. module.exports = (sequelize, DataTypes) => sequelize.d ...

In Chrome, the computed style of background-position is returned as 0% 0%

Let's say I have an element and I am interested in finding out its background-position: To achieve this, I use the following code snippet: window.getComputedStyle(element).getPropertyValue('background-position') If the value of background ...

"Error encountered when attempting to upload directory due to file size

Utilizing the webkit directory to upload a folder on the server has been successful, however, an issue arises when there are more than 20 files in the folder. In this scenario, only the first 20 files get uploaded. The PHP code used for uploading the fold ...

Incorporating post data into a Partial View

Main objective: My goal is to enable users to click on a specific day on the calendar plugin and have a popup Bootstrap modal display events scheduled for that day. Current Progress: I am currently utilizing a javascript plugin called fullCalendar. With ...

Issue with jQuery fadeTo() not working after appendTo() function completes

I am facing a problem with the code below that is meant to create a carousel effect for my website. The main issue I am encountering is that the original fadeTo() function does not actually fade the elements, but rather waits for the fade time to finish an ...

Developing a cascading dropdown feature for ASP.NET MVC using JSON

I am currently working on implementing a cascading drop-down list in ASP.NET MVC by following a tutorial. However, I'm encountering an issue where the first drop-down box is not loading with manufacturer data. I suspect there may be an error with the ...

Conquering cross-origin resource sharing (CORS) using XMLHttpRequest without relying on JSONP

Appreciate your time in reading this inquiry! For the past few days, I've been grappling with an AJAX request issue. Despite scouring through numerous answers on Stack Overflow, I'm still unable to find a resolution. Any assistance would be grea ...

Adding items to a JSON document

My task involves creating a pseudo cart page where clicking on checkout triggers a request to a JSON file named "ordersTest.json" with the structure: { "orders": [] }. The goal is to add the data from the post request into the orders array within the JSO ...

Troubleshooting problem with list rendering in a Nativescript-vue GridLayout

As a newcomer to nativescript, I am utilizing GridLayout in an attempt to optimize layout nesting for better performance. In my template, I have an image followed by a vertical list of four items next to it. However, only the first item on the list is visi ...

Building a 'Export to CSV' button using a PHP array within the Wordpress Admin interface

I have successfully populated a PHP multi-dimensional array using a custom function and now I want to enable my admin users to download the data. After researching, I came across a PHP function that can export an array to CSV file. I integrated this funct ...

Is it possible to display data on a webpage without using dynamic content, or do I need to rely on JavaScript

Imagine a scenario where I have a single-page website and I want to optimize the loading time by only displaying content below the fold when the user clicks on a link to access it. However, I don't want users with disabled JavaScript to miss out on th ...

Connecting JavaScript and jQuery scripts

Help needed! I am a beginner in the world of jQuery and JS. Unfortunately, my JS/jQuery code is not running and I can't figure out why. Can someone please take a look at my HTML and guide me on what might be causing the issue? Do I need to add some ad ...

An error occurred while attempting to retrieve data from a JSONArray

I have been working on creating a phonegap plugin for Android where I am returning a JSONArray using callBackContext.sendPluginResult(result);. Below is the code snippet demonstrating how I am constructing the JSONArray: private JSONArray makeJsonObject(S ...

Troubleshooting issues with rowspan in a Datatable

I am currently utilizing jQuery DataTables to display my grid data and implementing the rowspan concept with the rowsGroup option. Initially, it works well by spanning some rows and looking visually pleasing, but eventually, it starts failing. Here are so ...

Can anyone provide a solution for determining the number of active intervals in Javascript?

Similar Question: How to View All Timeouts and Intervals in JavaScript? I've been working on an HTML5 game that includes a lot of graphical effects using intervals created by the setInterval function. However, I've noticed that my game is ru ...