How to search using jQuery and SQL database in ASP.NET Core 3.1 project

Viewed 29

I am using ASP.NET Core 3.1 and tried to search a SQL database using ajax jQuery but encountered an error through the code I am using. The columns of the data table are displayed as "undefined".

Please help me solve this error.

This is my code - controller:

public JsonResult SearchBiodataJson(string SearchText)
{
    List<BiodatalistVM> list = _context.BiodataA
        .Where(x =>
            x.SurName.Contains(SearchText)
            ||
            x.OtherName.Contains(SearchText)
        )
        .Select(p => new BiodatalistVM
        {
            StaffId   = p.StaffId,
            SurName   = p.SurName,
            OtherName = p.OtherName,
            MDA       = p.MDA,
        })
        .ToList();

    return Json(list);
}

My view

    <input type="text" id="SearchText" class="form-control col-md-3" />
    
    <tbody id="tblBiodata">
@if(ViewBag.BiodataList != null)
{
    foreach (var item in ViewBag.BiodataList)
    {  
        <tr>
            <td>@item.StaffId</td>
            <td>@item.SurName</td>
            <td>@item.OtherName</td>
            <td>@item.MDA</td>
        </tr>
    }
}
    </tbody>
</table>

My jQuery code:

$(document).ready(function() {
    $("#SearchText").on("keyup", function() {
        var searchtext = $("#SearchText").val();
        $.ajax({
            type: "post",
            url: "/BiodataModels/SearchBiodataJson?SearchText=" + searchtext,
            success: function(result) {
                $("#tblBiodata").html("");

                if (result.length == 0) {
                    $("#tblBiodata").append("<tr><td colspan='4'>No Record Matched</td></tr>")
                }
                else {
                    $.each(result, function(index, value) {
                        var data = "<tr><td>" + value.StaffId + "</td>" + "<td>" + value.SurName + "</td>" + "<td>" + value.OtherName + "</td>" + "<td>" + value.MDA + "</td>";

                        $('#tblBiodata').append(data);
                    })
                } // if
            } // success
        }) // ajax
    }); // on #SearchText keyup
}); // ready

0 Answers
Related