Error on Ajax Uplaod

Jagjit Saini 106 Reputation points
2021-06-02T01:34:07.747+00:00

Hi

On this line i get error - $('#tblLocation').DataTable().ajax.reload();
DataTables warning: table id=tblLocation - Invalid JSON response. For more information about this error, please see http://datatables.net/tn/1
@foreach (var item in Model)
{
}
@azzedinehtmlsql .DisplayNameFor(model => model.Id)
@azzedinehtmlsql .DisplayNameFor(model => model.Description)
@azzedinehtmlsql .DisplayNameFor(model => model.IsActive)
Action
@azzedinehtmlsql .DisplayFor(modelItem => item.Id)
@azzedinehtmlsql .DisplayFor(modelItem => item.Description)
@azzedinehtmlsql .DisplayFor(modelItem => item.IsActive)
Edit Delete
****************************8
function Add() {
var res = validate();
if (res == false) {
return false;
}
var objLocation = {
Id: $('#txtId').val().toUpperCase(),
Description: $('#txtDescription').val().toUpperCase(),
IsActive: $('#txtIsActive').val().toUpperCase()
};
$.ajax({
url: "/Location/Add",
data: JSON.stringify(objLocation),
type: "POST",
contentType: "application/json;charset=utf-8",
dataType: "json",
success: function (result) {
$('#tblLocation').DataTable().ajax.reload();
$.notify(result.message, {
globalposition: "top center",
className:"success"
})
$('#myModal').modal('hide');
},
error: function (xhr, ajaxOptions, thrownError) {
$("#msgModalBody").html('Status : ' + xhr.status + ' Error : ' + thrownError);
$("#msgModal").modal('show');
}
});
}


public List<Location> GetAllLocation()
{
List<Location> objLocation = new List<Location>();
using (SqlConnection con = new SqlConnection(cs))
{
con.Open();
SqlCommand com = new SqlCommand("sp_Location", con);
com.CommandType = CommandType.StoredProcedure;
com.Parameters.AddWithValue("@朱大星 ", "R");
SqlDataReader rdr = com.ExecuteReader();
while (rdr.Read())
{
objLocation.Add(new Location
{
Id = rdr["Id"].ToString(),
Description = rdr["Description"].ToString(),
IsActive = rdr["IsActive"].ToString(),
});
}
return objLocation;
}
}

Thanks

Developer technologies | ASP.NET | Other
0 comments No comments
{count} votes

Accepted answer
  1. Yihui Sun-MSFT 806 Reputation points
    2021-06-02T08:46:14.813+00:00

    Hi @Jagjit Saini ,

    When loading data by Ajax (ajax), DataTables by default, expects the data loaded to be valid JSON.

    1. You did not give all the code, for example, how do you use DataTables to load data, so I can only speculate, you did not use ajax to load data.
      1. use ajax to load data
        var table = $('#tblLocation').DataTable({  
            ajax: {  
                url: "[@](/users/na/?userId=1a465025-7ffe-0003-0000-000000000000).Action("getallLocations","Home")",  
                dataSrc: 'objLocation'  
            },  
            columns: [  
                { data: "Id" },  
                { data: "Description" },  
                { data: "IsActive" }  
            ]  
        });  
        
    2. You can check the ajax.reload() method, you will find that it is used to reload the table data from the Ajax data source.
      1. table.ajax.reload();
    3. I wrote an example based on the code you provided, and you can check it out.
    4. You only need to change the method of querying data and the method of adding data to the database in my example to your own.

    Model

        public class Location  
        {  
            [Key]  
            public string Id { get; set; }  
            public string Description { get; set; }  
            public string IsActive { get; set; }  
        }  
    

    Controller

        public class HomeController : Controller  
        {  
            public DailyMVCDemoContext db = new DailyMVCDemoContext();  
            public ActionResult Index()  
            {  
                return View();  
            }  
            public ActionResult getallLocations()  
            {  
                var data = db.Locations.ToList();  
                return Json(new { objLocation = data },JsonRequestBehavior.AllowGet);  
            }  
            public ActionResult Add()  
            {  
                return PartialView("_AddView");  
            }  
            [HttpPost]  
            public ActionResult Add(Location  model)  
            {  
                db.Locations.Add(model);  
                db.SaveChanges();  
                return Json("", JsonRequestBehavior.AllowGet);  
            }  
        }  
    

    Index

    <button class="btn btn-primary" id="Addbtn">add</button>  
        <table class="table" id="tblLocation">  
            <thead>  
                <tr>  
                    <th>  
                        Id  
                    </th>  
                    <th>  
                        Description  
                    </th>  
                    <th>  
                        IsActive  
                    </th>  
                </tr>  
            </thead>  
        </table>  
        <div class="modal fade" id="myModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel">  
            <div class="modal-dialog" role="document">  
                <div class="modal-content">  
                    <div class="modal-header">  
                        <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>  
                        <h4 class="modal-title" id="myModalLabel">Modal title</h4>  
                    </div>  
                    <div class="modal-body">  
                    </div>  
                    <div class="modal-footer">  
                        <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>  
                        <button id="saveAdd" type="button" class="btn btn-primary">Save changes</button>  
                    </div>  
                </div>  
            </div>  
        </div>  
    

    JavaScript on Index View

    -You need to reference the dataTables.min.js file.

            var table = $('#tblLocation').DataTable({  
                ajax: {  
                    url: "@Url.Action("getallLocations","Home")",  
                    dataSrc: 'objLocation'  
                },  
                columns: [  
                    { data: "Id" },  
                    { data: "Description" },  
                    { data: "IsActive" }  
                ]  
            });  
            $("body").on("click", "#Addbtn", function () {  
                $.ajax({  
                    url: "@Url.Action("Add", "Home")",  
                    type: "Get",  
                    success: function (result) {  
                        $(".modal-body").html(result);  
                        $("#myModal").modal("show");  
                    }  
                });  
            });  
            $("body").on("click", "#saveAdd", function () {  
                var objLocation = {  
                    Id: $('#Id').val().toUpperCase(),  
                    Description: $('#Description').val().toUpperCase(),  
                    IsActive: $('#IsActive').val().toUpperCase()  
                };  
                $.ajax({  
                    url: "@Url.Action("Add", "Home")",  
                    data: JSON.stringify(objLocation),  
                    type: "POST",  
                    contentType: "application/json;charset=utf-8",  
                    dataType: "json",  
                    success: function (result) {  
                        table.ajax.reload();  
                        $("#myModal").modal("hide");  
                    }  
                });  
            });  
    

    _AddView Partial View

    @model WebApplication8.Models.Location  
    @Html.DisplayNameFor(m => m.Id)  
    @Html.TextBoxFor(m => m.Id, new { @class = "form-control" })  
    @Html.DisplayNameFor(m => m.Description)  
    @Html.TextBoxFor(m => m.Description, new { @class = "form-control" })  
    @Html.DisplayNameFor(m => m.IsActive)  
    @Html.TextBoxFor(m => m.IsActive, new { @class = "form-control" })  
    

    Result
    101683-result.gif


    If the answer is helpful, please click "Accept Answer" and upvote it.
    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.
    Best Regards,
    YihuiSun

    0 comments No comments

0 additional answers

Sort by: Most helpful

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.