[Solved] ASP.Net Core MVC jQuery Ajax NullReferenceException: Object reference not set to an instance of an object

trisetia302
 
on Dec 02, 2021 12:58 AM
Sample_818387.zip
721 Views

Hi Good Peoples,

I was tried to save data using ajax but always get the error message like this "NullReferenceException: Object reference not set to an instance of an object". 

Before I'm ever get the error message like that, when I added "[FromBody]" on headed controller the problem solved but now I do same way the problem not solved.

I was tried to solve this issue but I can't solve it yet.

I sure the value on the dropdownlist is not null. Where is the mistake in my code?

Any help could be apriciate.

This is the log of error message

NullReferenceException: Object reference not set to an instance of an object.
Penginapan_Apps.Controllers.PesananKamarController.UpdateStatusKamar(PesananKamarModel pesanan) in PesananKamarController.cs

The Controller

[HttpPost]
public JsonResult UpdateStatusKamar([FromBody] PesananKamarModel pesanan)
{
    int i;
    using(SqlConnection con = new SqlConnection(this._configuration.GetConnectionString("Penginapan_Apps")))
    {
        using(SqlCommand cmd = new SqlCommand("UpdateStatusKamar"))
        {
            con.Open();
            cmd.Connection = con;
            cmd.CommandType = System.Data.CommandType.StoredProcedure;
            cmd.Parameters.AddWithValue("@ID_Kamar",Convert.ToInt32(pesanan.ID_Kamar));
            cmd.Parameters.AddWithValue("@Status", pesanan.Status);
            i = cmd.ExecuteNonQuery();
            TempData["pesan"] = "Data berhasil disimpan..";
        }
    }
    return Json(i);
}

The Ajax

<script type="text/javascript" lang="javascript">
    $(document).ready(function () {
        $('#BtnSimpanPesananKamar').on("click", function () {
            var Status = {
                ID_Kamar: $("#DropdownListNomerKamar").val(),
                Status: $("#Status").val("Room Was Reservation")
            };
                $.ajax({
                url: "@Url.Action("UpdateStatusKamar", "PesananKamar")",
                data: JSON.stringify(Status),
                type: "POST",
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                    success: function () {
                        MessageSuccess();
                },
                error: function (errormessage) {
                    window.alert(errormessage.responseText);
                }
            });
        });
    });
    function MessageSuccess() {
        Swal.fire({
            position: 'top',
            icon: 'success',
            title: 'Good job!',
            text: 'Data berhasil disimpan...'
        });
    }
</script>
Download FREE API for Word, Excel and PDF in ASP.Net: Download
dharmendr
 
on Dec 04, 2021 01:24 AM
on Dec 04, 2021 01:28 AM

Hi trisetia302,

Check the below example.

Model

public class PersonModel
{
    public string CountryId { get; set; }
    public string Name { get; set; }
}

Controller

public class HomeController : Controller
{
    public IActionResult Index()
    {
        return View();
    }

    [HttpPost]
    public JsonResult AjaxMethod([FromBody]PersonModel person)
    {
        return Json(person);
    }
}

View

@addTagHelper*, Microsoft.AspNetCore.Mvc.TagHelpers
@model jQuery_AJAX_Core.Models.PersonModel
@{
    Layout = null;
}

<!DOCTYPE html>

<html>
<head>
    <meta name="viewport" content="width=device-width" />
    <title>Index</title>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css" />
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.2/css/bootstrap.min.css" />
    <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
</head>
<body class="container">
    <div class="col-md-6">
        <div class="position-relative form-group">
            <label asp-for="Name" class="control-label"></label>
            <input id="txtName" asp-for="Name" class="form-control" value="Mudassar Khan" />
            <br />
            Country: <select id="ddlCountries" asp-for="CountryId" class="form-control" name="CountryId" required>
                <option value="1">USA</option>
                <option value="2">India</option>
                <option value="3">Russia</option>
                <option value="4">France</option>
            </select>
        </div>
    </div>
    <button type="button" id="btnSave" name="Save" class="mt-1 btn btn-success"><i class="fa fa-save"> Save</i></button>
    <script type="text/javascript" lang="javascript">
    $(document).ready(function () {
        $('#btnSave').on("click", function () {
            $('#txtName').val("Mudassar Khan");
            var Status =
            {
                CountryId: $("#ddlCountries").val(),
                Name: $("#txtName").val()
            };
            $.ajax({
                url: "@Url.Action("AjaxMethod", "Home")",
                data: JSON.stringify(Status),
                type: "POST",
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                success: function () {
                    alert('Data saved successfully...');
                },
                error: function (errormessage) {
                    window.alert(errormessage.responseText);
                }
            });
        });
    });
    </script>
</body>
</html>

Screenshot

trisetia302
 
on Dec 04, 2021 04:28 AM

@dharmendr

Problem solved. you are amazing sir

Thank you very much for the guide and help sir,,

I just changed the dropdownlist and ajax. Everything went smoothly.

The Dropdownlist

<select id="DropdownListNomerKamar" asp-for="ID_Kamar" class="form-control" name="ID_Kamar" required>
    <option value="ID_Kamar"></option>
</select>

The Ajax for fill the dropdownlist

<script type="text/javascript" lang="javascript">
    $(document).ready(function () {
        $('#BtnCariIDTipeKamar').on("click", function () {
            $.ajax({
                url: "@Url.Action("CariAvailableRoom", "PesananKamar")",
                type: "GET",
                contentType: "application/json;charset=UTF-8",
                dataType: "json",
                data: { ID_Tipe_Kamar: $('#ID_Tipe_Kamar').val() },
                success: function (data) {
                    if (data != "") {
                        var ddlNoKamar = $("#DropdownListNomerKamar").empty();
                        $(data).each(function (index, item) {
                            ddlNoKamar.append($("<option></option>").val(item.ID_Kamar).html(item.ID_Kamar));
                        });
                    }
                    else {
                        window.alert(' error : ' + respons.message);
                    }
                }
            });
        });
    });
</script>