Error Encountered: "JSON Post Failure in ASP.net MVC resulting in 500

Whenever I attempt to send a variable to JSON on ASP.net MVC, I encounter the following error:

jquery-2.2.3.min.js:4 GET http://localhost:58525/Order/GetAddress/?userid=42&email=asandtsale%40gmail.com 500 (Internal Server Error)

This is my controller setup:

public JsonResult GetAddress(int uservalue, string email)
    {
        UserService rpuser = new UserService();
        DATA.Models.ORM.Entity.UserEntity.User userentity = rpuser.FirstOrDefault(x => x.Id == uservalue);
        Models.DTO.OrderDTO.NewAddressVM addressmodel = new Models.DTO.OrderDTO.NewAddressVM();
        addressmodel.FirstName = userentity.Name;
        return Json(addressmodel.FirstName, JsonRequestBehavior.AllowGet);
    }

Here's how my view looks like:

<script>
$(document).ready(function () {
    $("#okbutton").click(function () {
        var e = document.getElementById("emailadd");
        var uservalue = e.options[e.selectedIndex].value;
        var usertext = e.options[e.selectedIndex].text;
        var link = "/Order/GetAddress/";

        $.ajax({
            type: "GET",
            url: link,
            data: {userid: uservalue, email: usertext},
            success: function (result) {
                if (result == "accept") {
                    $("div#voucher-result").html('<span style="color:green; font-weight:bold;">Your voucher code is valid. Discount price: <text style="font-size:19px;">£50</text><br />If you complete your order you will get a discount of £50.</span>');
                } else {
                    $("div#voucher-result").html('<span style="color:green; font-weight:bold;">Your voucher code is valid. Discount price: <text style="font-size:19px;">£50</text><br />Else</span>');
                }
            }
        });
    });
});

Finally, here's the form part:

               <div class="row">
                    <div class="col-md-6">
                        <div class="form-group">
                            <label>Customer</label>
                            @Html.DropDownListFor(x => x.CustomerId, new SelectList(Model.CustomerList, "Id", "UserName"), new { @class = "form-control select2", @id="emailadd", @placeholder = "" })

                        </div>
                    </div>
                    <div class="col-md-6">
                        <label></label>
                        <button type="button" class="btn btn-block btn-success" id="okbutton" style="width:60px;">OK</button>
                    </div>
                    <div id="voucher-result"></div>
                </div>

Answer №1

GetAddress(int uservalue, string email)
requires the parameter uservalue to be passed, but in your javascript code, you are sending over a userid instead:
data: {userid: uservalue, email: usertext}

To resolve this issue, you need to either change the parameter name from uservalue to userid in your controller, or update userid to uservalue in your javascript.

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

Having trouble with installing the most recent versions of React App dependencies

After cloning a project from GitHub, I attempted to install dependencies using npm install, but encountered an error: npm ERR! code ERESOLVE npm ERR! ERESOLVE unable to resolve dependency tree npm ERR! npm ERR! While resolving: <a href="/cdn-cgi/l/email ...

GWT - Response missing from CallBack in REST Service communication

My REST service is located at: http://localhost:4242/myrestservice/getobject and it returns JSON data. On the other hand, my GWT client can be accessed at: http://localhost:4242/gwtclient. This client is designed to make asynchronous calls to the REST ser ...

How to convert primary information into JSON format without using backslashes in Swift and PHP

When my PHP code encounters JSON with "/n" and "/", it returns an error. Now, I am unsure whether I should update my PHP or Swift code. This is my PHP code: $json = file_get_contents('php://input'); $obj = json_decode($json, true); print_r($obj ...

export default select an option

Forgive me if my question comes off as naive, but I'm still learning the ropes. :-) I stumbled upon something perplexing in this GitHub file. I am aware that we can export or import default functions, but in this instance, the author has used: expo ...

What is the method for identifying which input field the user has chosen on a web page retrieved from a server?

I attempted the code below without achieving the desired outcome. Any assistance would be greatly appreciated. UIPasteboard *pb = [UIPasteboard generalPasteboard]; [pb setString:passwordName]; NSString *jScriptString; jScriptString = [NSString string ...

Having trouble grasping the error message "Uncaught Typerror Cannot Read Property of 0 Undefinded"?

As I embark on creating my very first ReactJS website with Node in the back-end, I encountered an issue in fetching and printing data. While I successfully displayed the names, pictures, and emails of project members from the server, I faced an error when ...

Locate every instance of items in an array within a string

My files have a structure similar to this: https://i.stack.imgur.com/KyaVY.png When a user conducts a search, they send an array to the backend. This array always includes at least one element. For example, if they send ['javascript'] to the b ...

How can I extract a substring using jQuery?

<script type="text/javascript"> $(function(){ $("a[rel='tab']").click(function(e){ e.preventDefault(); pageurl = $(this).attr('href'); $.ajax({url:pageurl+'?rel=tab',success: function(data){ $(&apos ...

The use of Buffer() is no longer recommended due to concerns regarding both security vulnerabilities and

I'm encountering an issue while trying to run a Discord bot. The code I'm using involves Buffer and it keeps generating errors specifically with this code snippet: const app = express(); app.get("/", (req,res) => { if((new Buffer(req.quer ...

Locate the item within an array that contains the most keys

Can you help me with a coding challenge? I have an array of objects set up like this: let items = [ { a: '', b: 2, c: 3 }, { a: '', b: '', c: 5, d: 10 }, ...

In JavaScript, apply a red color style to an appended list item every third time it is added

It should be something like this: <ul id="list"> <li>1</li> <li>2</li> <li style="color: red;">3</li> <- Text should be red ... <li style="color: red;">6</li> <- red ...

Internet Explorer is failing to show the results of an ajax call retrieved from the

Need help with this code block: $(document).ready(function() { dataToLoad = 'showresults=true'; $.ajax({ type: 'post', url: 'submit.php', da ...

When the component mounts in React using firestore and Redux, the onClick event is triggered instantly

I am facing an issue with my component that displays projects. Each project has a delete button, but for some reason, all delete buttons are being automatically triggered. I am using Redux and Firestore in my application. This behavior might be related to ...

Tips for effectively structuring material-ui Grid in rows

I am currently using the material-ui framework to create a form. Utilizing the Grid system, I want to achieve the following layout: <Grid container> <Grid item xs={4} /> <Grid item xs={4} /> <Grid item xs={4} /> </Gr ...

Is it possible for a route's URL in ui-router to be at the same level as another state while also utilizing $stateParams?

In my application, I want to implement a feature where hitting the same level of the URL will lead to either the baz state or the biz state with a parameter. angular.module('foo') .config(function($stateProvider){ $stateProvider .state(&apos ...

How can I retrieve the identifier in Socket.io?

Is there a way to retrieve the unique Id from the server using socket.io? I attempted using clients[socket.id] = socket; However, I encountered an error stating: connections property is deprecated. use getconnections() method Does anyone have any sugg ...

Add several additional views following an element within a View in Backbone

addDimensions: function (order_id, counter) { this.dimensionsView = new dimensionsView({ el: "#panel-boxes-" + order_id + "_" + counter, id: order_id, counter: counter }); $("#panel-boxes-" + order_id + "_1").append(this.dimensionsView.render().el) ...

Retrieve the HTML representation of a progress bar in Ext JS 3.4 prior to its rendering

Is it possible to obtain the HTML representation of a progress bar before it is rendered anywhere? I am currently using a custom renderer for rendering a progress column in a grid: renderer: function( value, metaData, record, rowIndex, colIndex, store ) ...

steps for retrieving final outcome from forkJoin

I am currently working with an array of userIds, such as: ['jd', 'abc']. My goal is to loop through these userIds and retrieve full names using an API. Ultimately, I aim to transform the initial array into [ {userId: 'jd', nam ...

Ways to verify the existence of a username in WordPress without the need to refresh the page

How can I check if a username exists in the database without refreshing the page in a Wordpress form using AJAX? I've tried implementing AJAX in Wordpress before but it didn't work. Can someone provide me with a piece of helpful code or a link to ...