Home > Net >  AJAX returns variables null when updating data using Bootstrap Model in NET Core MVC
AJAX returns variables null when updating data using Bootstrap Model in NET Core MVC

Time:10-06

I have a bootstrap model using ajax to update customer data. However, all variables return null even though there is information in the text boxes.

Customer.cs

public class Customer
{
    [Display(Name = "ID")]
    public int ID { get; set; }
    [Display(Name = "Customer ID")]
    public string? CID { get; set; }
    [Display(Name = "Last Name")]
    public string? LastName { get; set; }
    [Display(Name = "First Name")]
    public string? FirstName { get; set; }
}

Stored Procedure Update

SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE SP_UPDATE (@ID INTEGER, @CID NVARCHAR(100), @LastName NVARCHAR(100), @FirstName NVARCHAR(100))
AS
BEGIN
    UPDATE CUSTOMERDB SET CID = @CID, LastName = @LastName, FirstName = @FirstName WHERE ID = @ID
END
GO

Update void is saved in CustomerDB.cs in folder Models

public void UpdateCustomer(Customer ctm)
{
    using (SqlConnection con = new SqlConnection(DBcon))
    {
        SqlCommand cmd = new SqlCommand("SP_UPDATE", con);
        cmd.CommandType = CommandType.StoredProcedure;
        cmd.Parameters.AddWithValue("@ID", ctm.ID);
        cmd.Parameters.AddWithValue("@CID", ctm.CID);
        cmd.Parameters.AddWithValue("@LastName", ctm.LastName);
        cmd.Parameters.AddWithValue("@FirstName", ctm.FirstName);
        con.Open();
        cmd.ExecuteNonQuery();
        con.Close();
    }
}

Controller

public class CustomerController : Controller
{
    CustomerDB objCustomer = new CustomerDB();
    public IActionResult Index()
    {
        List<Customer> lstctm = new List<Customer>();
        lstctm = objCustomer.GetAllCustomers().ToList();
        return View(lstctm);
    }

    public IActionResult Update(Customer ctmupdate)
    {
        objCustomer.UpdateCustomer(ctmupdate);
        return View();
    }
}

Ajax function

function Update() {  
    var res = validate();  
    if (res == false) {  
        return false;  
    }  
    var empObj = {  
        ID: $('#txtID').val(),
        CID: $('#txtCID').val(),
        LastName: $('#txtLastName').val(),
        FirstName: $('#txtFirstName').val(),
    };  
    $.ajax({  
        url: "/Customer/Update",  
        data: JSON.stringify(empObj),  
        type: "POST",  
        contentType: "application/json;charset=utf-8",  
        dataType: "json",  
        success: function (result) { 
            $('#txtCID').val("");  
            $('#txtLastName').val("");  
            $('#txtFirstName').val("");  
        },  
        error: function (errormessage) {  
            alert(errormessage.responseText);  
        }  
    });
}

function validate() {
    var isValid = true;
    if ($('#txtCID').val().trim() == "") {
        $('#txtCID').css('border-color', 'Red');
        isValid = false;
    }
    else {
        $('#txtCID').css('border-color', 'lightgrey');
    }
    if ($('#txtLastName').val().trim() == "") {
        $('#txtLastName').css('border-color', 'Red');
        isValid = false;
    }
    else {
        $('#txtLastName').css('border-color', 'lightgrey');
    }
    if ($('#txtFirstName').val().trim() == "") {
        $('#txtFirstName').css('border-color', 'Red');
        isValid = false;
    }
    else {
        $('#txtFirstName').css('border-color', 'lightgrey');
    }
    return isValid;
}

Bootstrap Modal

<div  id="EditModal" tabindex="-1" role="dialog" aria-labelledby="editModalLabel" aria-hidden="true">
    <div  role="document">
        <div >
            <div >
                <h5  id="editModalLable">Edit Customer</h5>
                <button type="button"  data-bs-dismiss="modal" aria-label="Close">
                    <span aria-hidden="true">&times;</span>
                </button>
            </div>
            <div >
                <form>
                <div >
                    <label for="txtID">ID</label>
                    <input type="text"  id="txtID" name="ID" />
                </div>
                <div >
                    <label for="txtCID">Customer ID</label>
                    <input type="text"  id="txtCID" name="Customer ID" />
                </div>
                <div >
                    <label for="txtLastName">Last Name</label>
                    <input type="text"  id="txtLastName" name="Last Name" />
                </div>
                <div >
                    <label for="txtFirstName">First Name</label>
                    <input type="text"  id="txtFirstName" name="First Name" />
                </div>
                </form>
            </div>
            <div >
                <button type="submit"  onclick="Update();">Update</button>
                <button type="button"  data-bs-dismiss="modal">Close</button>
            </div>
        </div>
    </div>    
</div>

ID is the auto increment primary key which is auto incremented by SQL Server. The column ID will be hidden.

CodePudding user response:

Firstly try this:

[HttpPost]
public IActionResult Update(Customer ctmupdate)
{
    objCustomer.UpdateCustomer(ctmupdate);
    //return View(); dont return view on ajax calls if you expect json or the another data!
    return Json(""); // or some data
}

Secondly if this not works try this without reversing my first suggestion:

$.ajax({  
    url: "/Customer/Update",  
    data: empObj,  // i changed this line
    type: "POST",  
    //contentType: "application/json;charset=utf-8",  
    //dataType: "json",  
    success: function (result) { 
        $('#txtCID').val("");  
        $('#txtLastName').val("");  
        $('#txtFirstName').val("");  
    },  
    error: function (errormessage) {  
        alert(errormessage.responseText);  
    }  
});

Hope this helps.

Edit: I changed and tested the code you share, and i realized that you are sending with datatype json, actually you dont need it because .net automatically detects it and binding properties without using json type.

Another point is that, if you are sending data with ajax you may not need form tag in your code unless you serialize it and prevent default event.

It must work now with my changes, i tested it in my local.

  • Related