ASP.NET MVC querystring parameter mismatch detected

Having an issue with my querystring - I am calling a controller action using JavaScript in the following way:

if ((event >= 65) && (event <= 90) || (event >= 48) && (event <= 57)) {
    var focussed = document.activeElement.id;
    window.setTimeout(function () {
        alert(in2.value);
        location.href = "/CarSaldi/ListaArt?in1=" + in1.value + "&in2=" + in2.value + "&focus=" + focussed;
    }, 1000);
}

Where 'in2' is an input text that may contain a "+", for example, "milk+chocolate". However, when calling the controller action:

public ActionResult ListaArt(string in1, string in2, string cod, string focus)
{
    [...]
}

The value of string 'in2' ends up showing as "milk chocolate" instead of "milk+chocolate". It's essential to retain the "+" sign within the string.

Answer №1

Make sure to utilize the java script function encodeURIComponent when encoding URLs.

location.href = "/CarSaldi/ListaArt?in1=" + encodeURIComponent(in1.value) 
 + "&in2=" + encodeURIComponent(in2.value) + "&focus=" + encodeURIComponent(focussed);

Your code should be updated as shown below:

if ((event >= 65) && (event <= 90) || (event >= 48) && (event <= 57)) {
var focussed = document.activeElement.id;
window.setTimeout(function () {
    alert(in2.value);
    location.href = "/CarSaldi/ListaArt?in1=" + encodeURIComponent(in1.value) 
 + "&in2=" + encodeURIComponent(in2.value) + "&focus=" + encodeURIComponent(focussed);
  }, 1000);
}

Answer №2

To preserve special characters, remember to use

encodeURIComponent(yourParameter)
.

By following this approach, your special characters will not be lost.

Answer №3

When dealing with URLs, it is important to encode certain characters properly.

 +   =  %2B

Therefore, rather than using '+' in your URL, you should use '%2B' instead.

To view a comprehensive table of URL encoded characters, visit:

Answer №4

Protect your data by utilizing the special coding tool known as encodeURIComponent:

try out this snippet:

 encodeURIComponent(inputField.value)

Answer №5

When working with query strings in asp.net mvc, it is crucial to avoid using javascript and string concatenation. Instead, rely on Url.Action to ensure consistency. The structure of the querystring and pathinfo can vary depending on how your routes are defined, so using Url.Action provides flexibility for future route changes:

var uri = "@Url.Action("ListaArt", CarSaldi", new {in1="xxx", in2="yyy", focus="zzz"})".replace("&amp;","&");
// Replace the "placeholders" values to the real ones
uri = uri.replace("xxx", in1.value);
uri = uri.replace("yyy", in2.value);
uri = uri.replace("yyy", focussed);
location.href = uri;

Additionally, when dealing with the plus sign, be sure to utilize the encodeURIComponent method in Javascript:

uri = uri.replace("yyy", encodeURIComponent(in2.value));

Remember to use replace("&amp;","&") because Url.Action uses & instead of & in URLs. This is suitable for HTML but not for location.href property.

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

difficulties retrieving information with $http.jsonp

Here is the code snippet that I am working with: var url = 'http://someURL?arg1=test&arg2=test&callback=JSON_CALLBACK'; $http.jsonp(url) .success(function(data){ console.log(data.found); }); Despite receiving a status code of 200 o ...

Performing AJAX in Rails4 to update boolean values remotely

Suppose I have a model named Post which includes a boolean attribute called active. How can I efficiently modify this attribute to either true or false directly from the list of posts in index.html.erb using link_to or button_to helper along with remote: ...

Incorporating additional information into the database

When I run the code, I see a table and a button. After entering data in the prompts as instructed, the table does not get updated. I'm unsure why this is happening. Can someone please explain? <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Trans ...

Disable the button on page load condition

In the Mysql PHP setup, there is a page displaying a list of students with student_id, name, birthdate, and various buttons on each row. The objective is to make a certain button inactive if the student_id is found in another table called 'saral_tciss ...

What is the best method to add data to a child array located within a nested array?

Struggling to create an array that will display data in the following format: Healthcare -- Insights driven by data for improved healthcare -- Urban Analytics Transport -- Urban Analytics Cities -- Urban Analytics I have attempted ...

Tips for building an API using an app router in Next.js

After setting up my new project and using the app router as recommended in the latest version of Next.js, I am now looking to create an API. How can I go about creating and utilizing this API within my page app/user/page.tsx? I have already created an API ...

I can't seem to get my repeater to show the text, did I overlook something?

I am using a repeater to generate LinkButtons This is the code for the repeater: <asp:Repeater runat="server" ID="rptBreadCrumb" > <ItemTemplate> <div> <asp:LinkButton CssClass="process-breadcrumb" ID="lnkBrdC ...

PHP: run a function when a button is clicked

I am currently developing a PHP & mySQLi CRUD application. Within a functions.php file, I have implemented a function that handles deleting individual users: function delte_single_user() { if (isset($_GET['id'])) { global $con; $us ...

Numerous Cycles Stemming from a Single Answer

My goal is to display a list of products with their details, including a sublist of product models that are checked in the detailed list. The challenge is to achieve this using only one GET request. This means retrieving the JSON data of products once and ...

Creating element modules in EJS

After building experience with React, I am now faced with the task of using ejs in my current project. Specifically, I need to return multiple radio elements. My attempt at achieving this was through the following code: <% const renderRadios = (value, ...

Leveraging external files with Django template referencing

Having trouble including external JavaScript and CSS files in the head tags of my Django template. They only seem to work when placed before the closing body tag. Any idea why this is happening? Another issue I'm facing is that when using inheritance, ...

What is the reason behind Babel including this redundant line of code in my build?

While utilizing Babel 7 and Gulp 4 in conjunction, I have noticed that the subsequent line of code is repeated five times within my build: function _typeof(obj) { "@babel/helpers - typeof"; if (typeof Symbol === "function" && typeof Symbol.iterato ...

Tips for styling text in a textarea for blog or news articles

After developing a simple blog application using php, I have incorporated an html form with the main blog article written within a <textarea>. The functionality works well as the data is stored in a database and can be accessed by other pages. Despi ...

What is the best way to modify a particular value buried within a JavaScript object?

Within my node project, I am working with a JavaScript object like the one shown below: that.responseData = { fields: { id: { label: 'ID', value: objectRecord.id, info: '', ex ...

Encountering difficulties with showing contact images in phonegap using angularjs

In my project, I encountered an issue where I can fetch and display the contact photo using simple HTML and JavaScript. However, when I attempt to do the same using AngularJS model, I encounter an error. Below is the code snippet that I am struggling with: ...

Loading images incrementally using promises

Attempting to load images with different resolutions sequentially using promises. Even after making changes as per the first suggestion, only one image is getting loaded according to Chrome dev tools. function loadImage(src) { return new Promise(fun ...

Utilizing JavaScript and jQuery to make a query to mySQL

Looking to solve a SQL database query challenge using JavaScript or jQuery? Here's the scenario: I have a SQL db and typically use the following query to retrieve data based on distance from specified coordinates: SELECT id, ( 3959 * acos( cos( rad ...

Guide on replacing characters in Blogger using Javascript

I'm trying to change certain characters like [ngu1], [ngu2] to [chanquadi] using the following script: <script type='text/javascript'> var heo1 = document.querySelector(<.post-body>); var heo2 = heo1.replace("[ngu1]", "c ...

Cloned element does not trigger on click event

When using jQuery 1.10, I encountered an issue where cloning a div containing a button with a click event defined did not retain the click event on the cloned div. I have come across similar questions multiple times, and existing solutions advise using cl ...

Updating Angular Material theme variables during the build processIs this okay?

How can I easily customize the primary color of my angular 6 application to be different for development and production builds? Is there a simple solution to automatically change the primary color based on the build? ...