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

Axios - Show the error message returned from validation as [object Object]

Within my API, I include the following validation logic: $request->validate([ 'firstname' => 'required', 'lastname' => 'required', 'username' => 'required|unique:us ...

What could be causing Vuejs to not update elements promptly?

Currently, I am encountering a scenario where I am adding options to a select element using Vue.js when the @change event of that specific element is triggered. An issue arises where the new option is not 'registered' until I exit the function. ...

Using JavaScript and PHP to dynamically update a field based on two input values within a row of a table

Currently in the process of developing a dynamic profit margin calculator for a personal project. Overview Data is retrieved from a database table using SQL and PHP After necessary validations, the data is dynamically displayed as rows in an HTML table ...

Automatic keyboard suggestions not working for HTML search input using Ajax

I am currently working on a PHP web application that uses a MySql database. I have implemented a search suggestion box using ajax. The issue I am facing is that the suggestions can be selected with the mouse and auto-completed, but not when using the keybo ...

What is the best way to save newly added elements on a webpage that were submitted by the

I am looking for a way to save the changes made by users on my webpage so that they can navigate to different pages and come back without losing any added elements. These changes should be retained even when the user goes back to edit the webpage, but I pr ...

Unraveling unicode escape sequences in JavaScript strings

My code includes a string like \uC88B\uC544\uC694. When I use this string in a node repl (v7.4.0), it displays '좋아요' correctly. However, when I try to use the same string in the following code snippet, it does not work as ex ...

Encountering a "MissingSchemaError" while attempting to populate the database with mongoose-seeder

I am facing an issue while trying to populate a database using mongoose-seeder. Despite setting up the schema correctly, I keep encountering a MissingSchemaError which has left me puzzled. Here is a snippet from the file where I define the schema: const m ...

How to utilize string interpolation in Vue 3 template attribute with quotation marks

I'm struggling to make the method buildAbbrToolTip() utilize the dynamic data from column.m_parse_hi in order to display the correct text definition for an abbreviation in the tooltip. Currently, I'm encountering a console error that says TypeEr ...

Guide on troubleshooting Node TypeScript in Visual Studio Code when the JavaScript source is stored in a separate directory

When using Visual Studio Code, I am able to debug and step through the TypeScript source code of Main.ts. This is possible as long as the JavaScript and map files are located in the same folder as the TypeScript source. This setup works well in this struc ...

Adjusting the placement in Draw2D

I'm a newcomer to this library and I'm struggling to figure out how to properly size and position the canvas. If anyone could provide guidance on the best way to do this, I would greatly appreciate it. $(window).load(function () { // se ...

Is it false to say that false in Javascript is still false?

After conducting some research, it appears that the question I have in mind has not been asked before, or maybe it has slipped under my radar. A rational approach would be to consider the following logic: false && false === true false && true === false t ...

The ideal version of firebase for showing messages in the foreground

Looking to instantly display notifications as soon as they are received? I recently watched a video on Angular 8 + Firebase where version 7.6.0 was discussed. While the notification is displayed in the foreground for me, I find that I need to click on some ...

Having trouble with JavaScript function returning false?

I am trying to call a JavaScript function on an ASP.NET button client click event and want to prevent postback. The function is working, but it is not preventing the page from posting back. Here is my JavaScript code: function User2Check() { v ...

Triggering an event upon selecting a dropdown option

I'm currently working on a form that includes a dropdown menu. My goal is to display specific keywords for each trip when selected from the menu (preferably below the input field, as shown in the code snippet below). .show has been set to display:non ...

Looping through a JSON response to retrieve and display HTML content

I am working with Laravel 5.1 and have a function that calculates kilometers. public function calculateKilometers() { $startingPoint = Input::get('starting_point'); $destination = Input::get('destination'); $distanceMat ...

"Upon invoking the console log, an empty value is being returned when attempting to access the

Why is console.log returning a blank line when trying to retrieve the value of a text input variable? HTML <label for="subject">Subject</label> <input type="text" id=" ...

Switch up the like button for users who have previously liked a post

Greetings, I trust everything is going well. I am attempting to implement a feature where users can like a post or article created by others using a button. I have established a const function named "getAPostLikeRecord()," which retrieves a list of users w ...

Angular 2 - The constructor of a class cannot be called without using 'new' keyword

Currently, I am working on integrating the angular2-odata library into my project. This is the code snippet I have: @Injectable() class MyODataConfig extends ODataConfiguration { baseUrl = "http://localhost:54872/odata/"; } bootst ...

Rapid polygon merging with JavaScript

I have a large geoJSON file containing polygons and multi-polygons, totaling 2.5 MB in size. My goal is to merge all these shapes to display them on a map within a web browser environment. In my Python workflow, I am using shapely.ops.unary_union which p ...

Struggling to constrain a TextField component from material-ui and encountering an issue with the inputRef

Currently, I am attempting to restrict the length of an autocomplete textfield within my project. However, when I apply InputProps={{ maxLength: 2 }}, it throws an error stating that my inputRef.current is null. Even though I have set the ref in the inputR ...