0

I have a modal with input fields, i want to be able to capture user inputs in my controller action insert same into the database and display it datatable at the same time without reloading the page.

My Modal Code:

 @using (Html.BeginForm("AddVisitEntries", "Consultant", FormMethod.Post, new { @id = "frmPatientRecord", @class = "col-xs-12" }))
  {
                            <div class="modal-body">

                                <div class="form-horizontal">
                                    <div class="form-group">
                                        <label id="patientRegNo" class="control-label col-md-2">RegNo:</label>
                                        <div class="col-md-10">
                                            <input type="text" value="" id="patientRegNo" name="patientRegNo" class="form-control" />
                                        </div>
                                    </div>

                                    <div class="form-group">
                                        <label id="appointmentDate" class="control-label col-md-2">Date:</label>
                                        <div class="col-md-10">
                                            <div class='input-group date' id='datetimepicker'>
                                                <input type='text' class="form-control datetimepicker" id="appointmentDate" name="appointmentDate" />
                                                <span class="input-group-addon datetimepicker-addon">
                                                    <span class="glyphicon glyphicon-calendar"></span>
                                                </span>
                                            </div>
                                        </div>
                                    </div>
                                </div>

                            </div>
  }

My Action Method:

[Authorize(Roles = "Consulting")]
    public JsonResult InsertPatientAppointment(string patientRegNo, string appointmentDate)
    {

        if (patientRegNo != null)
        {    
          //Insert record   here    
           //retrieves records here and pass it to the below function
          var data = Newtonsoft.Json.JsonConvert.SerializeObject(approveList);
                    return Json(data);                  
           return Json(new { s = "Record inserted successfully!" });              
        }
        else
        {
            return Json(new { f = "Insertion failed, please try again later!" });
        }
   }

My Ajax function:

<script type="text/javascript">
   $(document).ready(function () {
    var table = $("#tblAppointment").DataTable();
    $("#saveButton").click(function () {

        $.ajax({
            url: '/Consultant/InsertPatientAppointment/',
            type: "POST",
            data: JSON.stringify({ appointmentDate: $("#appointmentDate"), 
patientRegNo: $("#patientRegNo").val(), }),
            cache: false,
            dataType: "json",
            success: function (_data) {
                $(".spina").hide();
                if (_data.f !== undefined) {
                    swal({
                        title: "Failed!",
                        text: _data.f,
                        type: "info"
                    });
                    table.clear().draw();
                    return false;
                }
                else {
                    swal({
                        title: "Success!",
                        text: _data.s,
                        type: "success"
                    });
                }

                var arr = $.map(JSON.parse(_data), function (el) { return el 
});
                //console.log(arr);
                if (arr.length === 0) {
                    swal({
                        title: "No Record Found!",
                        text: _data.f,
                        type: "info"
                    });
                    table.clear().draw();
                    return false;
                }
                table.clear();
                table.destroy();
                $('#tblAppointment').dataTable({
                    data: arr,
                    columns: [
                        { "data": "PatientRegNo" },
                        { "data": "AppointmentDate" },                                                       
                    ],
                    dom: 'Bfrtip',
                    buttons: [
                        'copy', 'csv', 'excel',
                        {
                            extend: 'pdfHtml5',
                            orientation: 'Portriat',
                            pageSize: 'A4'
                        }
                    ]
                });
                table = $("#tblAppointment").DataTable();
            }
        });
    });
 });

</script>

My modal displays well, but each time i enter input and click on the save button, the values in the controller action are always null, i want to be able to send user input to the controller action, insert and displays same on datatable without reloading the page, any assistance will be appreciated.

UwakPeter
  • 341
  • 2
  • 6
  • 26
  • if you add a breakpoint on InsertPatientAppointment do you even get there when clicking the save button? It's been a while since I work with this.. but I think you're doing it wrong.. check out https://stackoverflow.com/questions/21578814/how-to-receive-json-as-an-mvc-5-action-method-parameter – rmjoia Nov 07 '18 at 16:07
  • yes, it breaks, the argument values are nulls – UwakPeter Nov 07 '18 at 16:10
  • I think you have to use [FromBody] to get them from the form or create an object that has the same properties, than the framework will try parse the json into the expected object... I'm not sure.. check the link on my previous comment. – rmjoia Nov 07 '18 at 16:12
  • This doesn't work for me, i have a datatable on the same view, my view model for the datatable is a list of type IEnumerator, or is there any way i can tweak this to still suit my purpose? – UwakPeter Nov 08 '18 at 10:38

1 Answers1

0

What happens is that, you need to model your data as the expected JSON you're posting.

In the following example, I created the type myType with the properties you show on your example and the json is parsed in to the correct type with the properties populated as you expect.

You can read more here Call a Web API From a .NET Client (C#), although I would say that it works not only from a .NET client, but any client..

You can also check this link here with some examples too:
How to receive JSON as an MVC 5 action method parameter

[HttpPost]
public JsonResult InsertPatientAppointment(myType myType)
{

    return new JsonResult(new
    {
        myType.patientRegNo,
        myType.appointmentDate
    });
}

public class myType {
    public string patientRegNo { get; set; }
    public string appointmentDate { get; set; }
}

Tested myself with postman.. it works. I also tried your implementation and was null indeed.

Hope it helps.

rmjoia
  • 962
  • 12
  • 21
  • This doesn't work for me, i have a datatable on the same view, my view model for the datatable is a list of type IEnumerator, or is there any way i can tweak this to still suit my purpose? – UwakPeter Nov 08 '18 at 10:38
  • The example I posted shows how to receive JSON format in a POST request and not getting null.. but the value I sent.. the implementation details of your modal window I didn't test. I suppose you can setup a simple git repo with the functionality you want to that people can try to help (including myself). Since I didn't have the UI, I used Postman to send a post request with a JSON Object with the data it seemed you were using. To be honest, I think the UI is just an implementation detail, and your endpoint has to handle any POST request that fulfils the requirements. – rmjoia Nov 08 '18 at 15:59
  • Thanks, i was able to make it work! i created a viewmodal of same properties on the modal, and when i posted it, i was able to get user input values from the view modal object – UwakPeter Nov 09 '18 at 09:01
  • that was what I was trying to show on the example, I will edit it to be more explicit – rmjoia Nov 09 '18 at 10:30