0
votes

I have a problem with my code. The problem is I am not getting post data by parameter using ajax.

Can anyone fix this? The code is shown below.

This is Javascript Ajax code where I am sending data by post method to the controller:

$('#pending').click(function () {
    SaveTestResult("/Reception/PatientTests/SavePendingTest");
});

function SaveTestResult(url) {
    var pid = $('.patientId').attr('id');
    var tid = "";
    var tval = "";
    var tpid = "";
    var tests = [];

    $("table > tbody > tr").each(function () {
        testId = $(this).find('.tid').val();

        if(typeof(testId) != "undefined")
        {
            tid = testId;
        }

        var rowText = ""

        $(this).find('td').each(function () {
            tpid = $(this).find('.tpId').val();
            tval = $(this).find('.result').val();

            if (typeof (tpid) != "undefined") {
                tests.push({ PatientId: pid, TestId: tid, TestParameterId: tpid, TestValue: tval });
            }
        });
    });

    // alert(JSON.stringify(tests));   
    $.ajax({
            type: "POST",
            url: url,
            data: JSON.stringify(tests),
            headers: { "RequestVerificationToken": $('input[name="__RequestVerificationToken"]').val() },
            success: function (data) {
                alert(data);
            },
            error: function (e) {
                alert('Error' + JSON.stringify(e));
            }
    });
}

This is the controller:

[HttpPost]
public async Task<IActionResult> SavePendingTest(List<PendingTestResult> pendingTestResult)
{
    if (ModelState.IsValid)
    {
        foreach (PendingTestResult ptr in pendingTestResult)
        {
            _db.Add(ptr);
            await _db.SaveChangesAsync();
        }

        return RedirectToAction(nameof(Index));
    }

    return View();
}

And this is the model class:

public class PendingTestResult
{
    [Key]
    public int Id { get; set; }
    [Display(Name = "Patient Id")]
    public int PatientId { get; set; }

    [Display(Name = "Test Id")]
    public int TestId { get; set; }

    [Display(Name = "Test Parameter")]
    public int TestParameterId { get; set; }
    public string TestValue { get; set; }

    [Display(Name = "Test")]
    [ForeignKey("TestId")]
    //relation of Tests table
    public virtual Tests Tests { get; set; }

    [Display(Name = "Patient")]
    [ForeignKey("PatientId")]
    //relation of Patient table
    public virtual Patient Patient { get; set; }

    [Display(Name = "Test Parameter")]
    [ForeignKey("TestId")]
    //relation of Patient table
    public virtual TestParameter TestParameter { get; set; }
}

this is the view

@model DeltaSoftLIS.Models.Patient_Tests_TestParameter


@{
    ViewData["Title"] = "Test Result";
    Layout = "~/Views/Shared/_Layout.cshtml";
}

<div class="container-fluid">
    <div class="row">
        <div class="col-md-3">
            <div class="card">
                <partial name="_SidebarMenuPartialReception" />
            </div>
        </div>
        <div class="col-md-9 animated bounce">
            <div class="card" style="padding:20px 50px;">
                <div class="row">
                    <div class="col-md-6">
                        <h2 class="text-info">Test Result</h2>
                    </div>
                </div>
                <br />

                <div class="row blue-gradient mb-4">
                    <div class="col-md-3">
                        <form asp-action="TestResult" method="post" class="form-inline">
                            <div class="form-group">
                                <label class="text-white">Visit Number &nbsp;</label>
                                <input type="text" class="form-control" id="visitNo" asp-for="patient.VisitNo" />
                                <input type="submit" value="Submit" class="btn blue-gradient" />
                            </div>
                        </form>
                    </div>
                </div>
                @if (ViewBag.error != null)
                {
                    <div class="alert alert-danger">@ViewBag.error</div>
                }
                else
                {
                    <div class="container">
                        <div class="row">

                            @if (Model != null)
                            {
                                <div class="col-md-2">
                                    Visit No: <span id="patinet.visitNo">@Model.patient.VisitNo</span>
                                </div>
                                <div class="col-md-4">
                                    Patient Name: <span style="text-transform:capitalize" class="patientId" id="@Model.patient.Id">@Model.patient.FirstName @Model.patient.MiddleName @Model.patient.LastName</span>
                                </div>
                            }
                        </div>
                    </div>
                    @if (ViewBag.test != null)
                    {
                        <div class="container p-4">
                            <form>
                            <table class="table table-bordered table-sm" style="height:auto">
                                <tr class="blue-gradient-rgba text-white">
                                    <th>Test Name</th>
                                    <th>Value</th>
                                    <th>Unit</th>
                                    <th>Normal</th>
                                    <th>Minimum</th>
                                    <th>Maximum</th>
                                </tr>
                                 @{string testgroup = "";
                                     }

                                     @foreach (var data in ViewBag.test)
                                     {
                                        <tr>
                                            @if (testgroup != data.Tests.TestName)
                                            {
                                                <input type="hidden" class="tid" value="@data.Tests.Id" />
                                                <th colspan="2">@data.Tests.TestName</th>

                                            }
                                            @{testgroup = data.Tests.TestName;
                                            }
                                        </tr>
                                        @foreach (var tp in ViewBag.testPara)
                                        {
                                            if (data.Tests.Id == tp.TestId)
                                            {
                                                <tr>
                                                    <td>@tp.ParameterName</td>
                                                    <td><input type="hidden" class="tpId" value="@tp.Id"><input type="text" class="result"></td>
                                                    <td>@tp.Unit</td>
                                                    <td>@tp.NormalRange</td>
                                                    <td>@tp.Minimum</td>
                                                    <td>@tp.Maximum</td>
                                                </tr>
                                            }
                                        }
                                    }
                                

                            </table>
                            </form>
                        </div>
                    }

                }
                <div class="row">
     
                    <div class="col-md-12 text-right">
                        @*@Html.ActionLink("Print Receipt", "printReceipt", new { id = Model.Id },new { taget = "_blank" }) |*@

                        <a asp-action="Index">Back to List</a> |
                        <input type="button" value="Pending" id="pending" class="btn sunny-morning-gradient text-white" />
                        <input type="button" value="Complete" id="complete" class="btn blue-gradient" />
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

<script>
    $(document).ready(function () {
        $('.result').keyup(function () {
            var value = $(this).val();
            var min = parseFloat($(this).closest('tr').find("td:eq(4)").text());
            var max = parseFloat($(this).closest('tr').find("td:eq(5)").text());
            if (value < min) {
                $('.result').css({ 'color': 'blue' })
            }
            else if (value > max) {
                $('.result').css({ 'color': 'red' })
            }
            else {
                $('.result').css({ 'color': 'green' })
            }
        });

        $('#pending').click(function () {
            SaveTestResult("/Reception/PatientTests/SavePendingTest");
        });
        function SaveTestResult(url) {
            var pid = $('.patientId').attr('id');
            var tid = "";
            var tval = "";
            var tpid = "";
            var tests = [];
            $("table > tbody > tr").each(function () {
                
                testId = $(this).find('.tid').val();
                
                if(typeof(testId) != "undefined")
                {
                    tid = testId;
                }
                 
                var rowText = ""
                
                $(this).find('td').each(function () {

                    tpid = $(this).find('.tpId').val();
                    tval = $(this).find('.result').val();
                    if (typeof (tpid) != "undefined") {
                        tests.push({ PatientId: pid, TestId: tid, TestParameterId: tpid, TestValue: tval });
                    }
                });
                 
            });
            //alert(JSON.stringify(tests));   
            $.ajax({
                type: "POST",
                url: url,
                data: JSON.stringify(tests),
                 contentType: "application/json",
                headers: { "RequestVerificationToken": $('input[name="__RequestVerificationToken"]').val() },
                success: function (data) {
                    
                    alert(data);
                },
                error: function (e) {
                    alert('Error' + JSON.stringify(e));
                }
            });
        }
    });
</script>

Please help me resolve this issue and save the list into the database

error in console log: Error{"readyState":4,"responseText":"System.InvalidOperationException: The view 'SavePendingTest' was not found. The following locations were searched:\r\n/Areas/Reception/Views/PatientTests/SavePendingTest.cshtml\r\n/Areas/Reception/Views/Shared/SavePendingTest.cshtml\r\n/Views/Shared/SavePendingTest.cshtml\r\n/Pages/Shared/SavePendingTest.cshtml\r\n at Microsoft.AspNetCore.Mvc.ViewEngines.ViewEngineResult.EnsureSuccessful(IEnumerable`1 originalLocations)\r\n at Microsoft.AspNetCore.Mvc.ViewFeatures.ViewResultExecutor.ExecuteAsync(ActionContext context, ViewResult result)\r\n at Microsoft.AspNetCore.Mvc.ViewResult.ExecuteResultAsync(ActionContext context)\r\n at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.g__Awaited|29_0[TFilter,TFilterAsync](ResourceInvoker invoker, Task lastTask, State next, Scope scope, Object state, Boolean isCompleted)\r\n at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.Rethrow(ResultExecutedContextSealed context)\r\n at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.ResultNext[TFilter,TFilterAsync](State& next, Scope& scope, Object& state, Boolean& isCompleted)\r\n at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.InvokeResultFilters()\r\n--- End of stack trace from previous location where exception was thrown ---\r\n at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.g__Awaited|24_0(ResourceInvoker invoker, Task lastTask, State next, Scope scope, Object state, Boolean isCompleted)\r\n at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.Rethrow(ResourceExecutedContextSealed context)\r\n at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.Next(State& next, Scope& scope, Object& state, Boolean& isCompleted)\r\n at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.InvokeFilterPipelineAsync()\r\n--- End of stack trace from previous location where exception was thrown ---\r\n at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.g__Logged|17_1(ResourceInvoker invoker)\r\n at Microsoft.AspNetCore.Routing.EndpointMiddleware.g__AwaitRequestTask|6_0(Endpoint endpoint, Task requestTask, ILogger logger)\r\n at Microsoft.AspNetCore.Authorization.AuthorizationMiddleware.Invoke(HttpContext context)\r\n at Microsoft.AspNetCore.Authentication.AuthenticationMiddleware.Invoke(HttpContext context)\r\n at Microsoft.AspNetCore.Diagnostics.EntityFrameworkCore.MigrationsEndPointMiddleware.Invoke(HttpContext context)\r\n at Microsoft.AspNetCore.Diagnostics.EntityFrameworkCore.DatabaseErrorPageMiddleware.Invoke(HttpContext httpContext)\r\n at Microsoft.AspNetCore.Diagnostics.EntityFrameworkCore.DatabaseErrorPageMiddleware.Invoke(HttpContext httpContext)\r\n at Microsoft.AspNetCore.Diagnostics.DeveloperExceptionPageMiddleware.Invoke(HttpContext context)\r\n\r\nHEADERS\r\n=======\r\nAccept: /\r\nAccept-Encoding: gzip, deflate, br\r\nAccept-Language: en-US,en;q=0.9\r\nConnection: close\r\nContent-Length: 351\r\nContent-Type: application/json\r\nCookie: .AspNetCore.Antiforgery.N4je5mEcjHk=CfDJ8AIMWfGHX55FkS_e4YdMcbzY3x_6D6NUruknobs5IXFtvGUf98iczXoLcdV3uv0upJtPUqZsVfh1caiPUHsNj2Vd3ruV4MaiVmYVhItLdcLgp_MdoGjsQSz9kgTULqP-8VAt44Gei1H65bSR9M0eaTg\r\nHost: localhost:44336\r\nReferer: https://localhost:44336/Reception/PatientTests/TestResult\r\nUser-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/80.0.3987.163 Safari/537.36\r\nrequestverificationtoken: CfDJ8AIMWfGHX55FkS_e4YdMcby-1dlSJss8EVbTOCIx1QPIjmq7HT5S65FLY_pNB67tGWoUF_1VICPa7tsrXvltyFQpalaUJrpQZcMbj_Yb5Ned8Q9Za3Teyq6FC8gCbk50v_NZj396PEQiVHpOMLrkxEk\r\nsec-fetch-dest: empty\r\nx-requested-with: XMLHttpRequest\r\norigin: https://localhost:44336\r\nsec-fetch-site: same-origin\r\nsec-fetch-mode: cors\r\n","status":500,"statusText":"error"}

1
What's error you have seen?mhkarami97
Did you pass the correct data in your tests?You could use console.log(tests) to see the data in your browser.Rena
Post request hit the server or not?shalitha senanayaka

1 Answers

0
votes

Add contentType: "application/json" to specify the type of data you're sending.If you do not specify it,it would use application/x-www-form-urlencoded; charset=UTF-8 by default:

 $.ajax({
        contentType: "application/json",           
});

And add [FromBody] to your action:

[HttpPost]
public async Task<IActionResult> SavePendingTest([FromBody]List<PendingTestResult> pendingTestResult)
{
    //...
}

UPDATE:

Model:

public class Patient_Tests_TestParameter
{
    public Patient patient { get; set; }
}
public class PendingTestResult
{
    [Key]
    public int Id { get; set; }
    [Display(Name = "Patient Id")]
    public int PatientId { get; set; }

    [Display(Name = "Test Id")]
    public int TestId { get; set; }

    [Display(Name = "Test Parameter")]
    public int TestParameterId { get; set; }
    public string TestValue { get; set; }

    [Display(Name = "Test")]
    [ForeignKey("TestId")]
    //relation of Tests table
    public virtual Tests Tests { get; set; }

    [Display(Name = "Patient")]
    [ForeignKey("PatientId")]
    //relation of Patient table
    public virtual Patient Patient { get; set; }

    [Display(Name = "Test Parameter")]
    [ForeignKey("TestId")]
    //relation of Patient table
    public virtual TestParameter TestParameter { get; set; }
}

public class TestParameter
{
    public int Id { get; set; }
    public int TestId { get; set; }
    public Test Test { get; set; }
    public int PatientId { get; set; }
    public Patient Patient { get; set; }
    public string ParameterName { get; set; }
}

public class Patient
{
    public int Id { get; set; }
    public string FirstName { get; set; }
    public string MiddleName { get; set; }
    public string LastName { get; set; }
    public List<TestParameter> TestParameter { get; set; }
}

public class Tests
{
    public int Id { get; set; }
    public string TestName { get; set; }
    public List<TestParameter> TestParameter { get; set; }

}

View:

@model Patient_Tests_TestParameter

<div class="container-fluid">
    <div class="row">
        <div class="col-md-9 animated bounce">
            <div class="card" style="padding:20px 50px;">
                <div class="row">
                    <div class="col-md-6">
                        <h2 class="text-info">Test Result</h2>
                    </div>
                </div>
                <br />

                @if (ViewBag.error != null)
                {
                    <div class="alert alert-danger">@ViewBag.error</div>
                }
                else
                {
                    <div class="container">
                        <div class="row">

                            @if (Model != null)
                            {
                                <div class="col-md-4">
                                    Patient Name: <span style="text-transform:capitalize" class="patientId" id="@Model.patient.Id">@Model.patient.FirstName @Model.patient.MiddleName @Model.patient.LastName</span>
                                </div>
                            }
                        </div>
                    </div>
                    @if (ViewBag.test != null)
                    {
                        <div class="container p-4">
                            <form>
                                <table class="table table-bordered table-sm" style="height:auto">
                                    <tr class="blue-gradient-rgba text-white">
                                        <th>Test Name</th>
                                        <th>Value</th>
                                    </tr>
                                    @{string testgroup = "";
                                    }

                                    @foreach (var data in ViewBag.test)
                                    {
                                        <tr>
                                            @if (testgroup != data.Tests.TestName)
                                            {
                                                <input type="hidden" class="tid" value="@data.Tests.Id" />
                                                <th colspan="2">@data.Tests.TestName</th>

                                            }
                                            @{testgroup = data.Tests.TestName;
                                            }
                                        </tr>
                                        @foreach (var tp in ViewBag.testPara)
                                        {
                                            if (data.Tests.Id == tp.TestId)
                                            {
                                                <tr>
                                                    <td>@tp.ParameterName</td>
                                                    <td><input type="hidden" class="tpId" value="@tp.Id">
                                                        <input type="text" class="result">
                                                    </td>
                                                </tr>
                                            }
                                        }
                                    }


                                </table>
                            </form>
                        </div>
                    }

                }
                <div class="row">

                    <div class="col-md-12 text-right">
                        @*@Html.ActionLink("Print Receipt", "printReceipt", new { id = Model.Id },new { taget = "_blank" }) |*@

                        <a asp-action="Index">Back to List</a> |
                        <input type="button" value="Pending" id="pending" class="btn sunny-morning-gradient text-white" />
                        <input type="button" value="Complete" id="complete" class="btn blue-gradient" />
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

@section Scripts
{
    <script>
        $(document).ready(function () {


            $('#pending').click(function () {
                SaveTestResult("/Reception/PatientTests/SavePendingTest");
            });
            function SaveTestResult(url) {
                var pid = $('.patientId').attr('id');
                var tid = "";
                var tval = "";
                var tpid = "";
                var tests = [];
                $("table > tbody > tr").each(function () {

                    testId = $(this).find('.tid').val();

                    if (typeof (testId) != "undefined") {
                        tid = testId;
                    }

                    var rowText = ""

                    $(this).find('td').each(function () {

                        tpid = $(this).find('.tpId').val();
                        tval = $(this).find('.result').val();
                        if (typeof (tpid) != "undefined") {
                            tests.push({ PatientId: pid, TestId: tid, TestParameterId: tpid, TestValue: tval });
                        }
                    });

                });
                //alert(JSON.stringify(tests));
                $.ajax({
                    type: "POST",
                    url: url,
                    data: JSON.stringify(tests),
                    contentType: "application/json",
                    headers: { "RequestVerificationToken": $('input[name="__RequestVerificationToken"]').val() },
                    success: function (data) {

                        alert(data);
                    },
                    error: function (e) {
                        alert('Error' + JSON.stringify(e));
                    }
                });
            }
        });
    </script>
}

Action:

public IActionResult Index()
{
    var model = new Patient_Tests_TestParameter()
    {
        patient = new Patient()
        {
            Id = 1,
            FirstName = "Patient1",
            LastName = "PatientLast",
            MiddleName = "PationtMiddle"
        }
    };
    ViewBag.test = new List<PendingTestResult>()
    {
        new PendingTestResult(){  Tests = new Tests(){  Id=1, TestName="test1"} },
        new PendingTestResult(){  Tests = new Tests(){  Id=2, TestName="test2"} },
        new PendingTestResult(){  Tests = new Tests(){  Id=3, TestName="test3"} }
    };
    ViewBag.testPara = new List<TestParameter>()
    {
        new TestParameter(){ Id=1, TestId=1, ParameterName="Para1"},
        new TestParameter(){ Id=2, TestId=1, ParameterName="Para2"},
        new TestParameter(){ Id=3, TestId=2, ParameterName="Para3"},
    };
    return View(model);
}

Result: enter image description here

UPDATE2:

[HttpPost]
[Route("Reception/PatientTests/SavePendingTest")]
public async Task<IActionResult> SavePendingTest([FromBody]List<PendingTestResult> pendingTestResult)
{
    if (ModelState.IsValid)
    {
        foreach (PendingTestResult ptr in pendingTestResult)
        {
            _db.Add(ptr);
            await _db.SaveChangesAsync();
        }

        return new JsonResult("/Home/Index");
    }

    return new JsonResult("/Home/Privacy");
}

Change your ajax success function:

$.ajax({
    type: "POST",
    url: url,
    data: JSON.stringify(tests),
    contentType: "application/json",
    headers: { "RequestVerificationToken": $('input[name="__RequestVerificationToken"]').val() },
    success: function (data) {
        //change this
        window.location.href = data;
    },
    error: function (e) {
        alert('Error' + JSON.stringify(e));
    }
});