Search code examples
javascriptjsonasp.net-mvcjsonresult

500 Internal Server Error on JSON Post ASP.net MVC


When I try to send a variable to JSON on ASP.net MVC, I am getting error like below:

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

My controller:

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);
    }

View:

<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>');
                }
            }
        });
    });
});

And Form:

               <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>

Solution

  • GetAddress(int uservalue, string email) expects a parameter called uservalue but in your javascript you are sending over an userid: data: {userid: uservalue, email: usertext}

    You should change the parameter uservalue to userid in your controller or change userid to uservalue in your javascript.