System.NullReferenceException: 'Object reference not set to an instance of an object.' AJAX

EB 1 Reputation point
2021-08-10T18:33:59.13+00:00

I have a view that contains a partial view. I have a javascript function that updates the partial view. When I initiate the java with a change of a ddl all works fine.
But when I try to do the exact same thing when a button is clicked I get the error message: System.NullReferenceException: 'Object reference not set to an instance of an object on my partial view page.

Here is the code that works:

        $(function () {
            $("#NewCustomer").change(function () {
                $.ajax({
                    type: "Get",
                    url: '/LO/ChangeDrop',
                    data: { Cust: $("#Cust").val() },
                    dataType: "html",
                    success: function (data) {
                        $("#myPartialView").html(data); // HTML DOM replac
                    }
                });

            });
        })

Here is the code that does notwork:

        $(function () {
            $("#btn").click(function () {
                $.ajax({
                    type: "Get",
                    url: '/LO/ChangeDrop',
                    data: { Cust: $("#Cust").val() },
                    dataType: "html",
                    success: function (data) {
                        $("#myPartialView").html(data); // HTML DOM replac
                    }
                });

            });
        })


<input type="submit" value="Search" id="btn">

Partial View:
@foreach (var item in Model)
{
<table style="width: 100%">
<tr>
<td style="width:100px">@item.CUSTNO</td>
<td style="text-align:left;width:200px">@item.PRTNAM</td>
<td style="text-align:left;width:500px">@item.ADDR</td>
</tr>
</table>

Any ideas? Let me know if you need more of the code.

Thanks

ASP.NET
ASP.NET
A set of technologies in the .NET Framework for building web applications and XML web services.
3,270 questions
0 comments No comments
{count} votes

1 answer

Sort by: Most helpful
  1. AgaveJoe 26,136 Reputation points
    2021-08-10T20:54:21.777+00:00

    The first step is to figure out what is null. Usually the error message tells you exactly what is null. Once you know what is null then you can backtrack to figure out why the item is not initialized. Unfortunately, you did not include all the relevant code like the actual markup and how the model is populated. Since #btn is a submit button it can cause a POST and a full page refresh depending on the markup design. Maybe you just need to cancel the POST? Otherwise, share enough code to reproduce this issue so the community is not forced to guess.

        $(function () {
            $("#btn").click(function (e) {
                e.preventDefault();
    
    1 person found this answer helpful.