locked
Cant Post Form Data to Custom Handler... RRS feed

  • Question

  • User-1042970710 posted

    Hello Folks,

    I have the following form and java script in my ASP.NET Core Razor Page.

    Here is the form :

     <form id="updatetaskdetails" method="post">
                        <div class="modal-body">
                            <input type="hidden" class="form-control" id="TaskID" value="@Model.taskDetails.TaskID">
                            <input type="hidden" class="form-control" id="TaskDetailsId">
                            <div class="form-group">
                                <label for="IncidentDate" class="col-form-label">تاريخ النشاط</label>
                                <input type="date" class="form-control" id="IncidentDate">
                            </div>
                            <div class="form-group">
                                <label for="TaskDetailsName" class="col-form-label">اسم نشاط</label>
                                <input type="text" class="form-control" id="TaskDetailsName">
                            </div>
                            <div class="form-group">
                                <label for="TaskDetailsDesc" class="col-form-label">نشاط</label>
                                <textarea class="form-control" id="TaskDetailsDesc"></textarea>
                            </div>
                        </div>
                        <div class="modal-footer">
                            <button type="button" class="btn btn-secondary" data-dismiss="modal">أغلق</button>
                            <button id="UpdateDetails" type="button" class="btn btn-primary">تحديث التفاصيل</button>
                        </div>
                    </form>

    Here is the code from where I fill  values the form using Jquery 

    <script>
            $('#updatedetail').click(function () {
    
                $('input:checkbox[name=TaskDetailsID]').each(function () {
                    if ($(this).is(':checked')) {
    
                        var TaskDetailsID = $(this).val();
                        var dataToPost = TaskDetailsID;
    
                        $.getJSON("/TaskDetails?handler=DetailByID", { dataToPost: dataToPost }, function (TaskDetails) {
    
                            var taskdetail = jQuery.parseJSON(TaskDetails);
    
                            $(".modal-body #TaskID").attr('value',taskdetail.TaskID);
    
                            $(".modal-body #TaskDetailsId").attr('value', taskdetail.TaskDetailsId);
                            $(".modal-body #IncidentDate").attr('value', taskdetail.IncidentDate.substr(0, 10));
                            $(".modal-body #TaskDetailsName").attr('value', taskdetail.TaskDetailsName);
                            $(".modal-body #TaskDetailsDesc").val(taskdetail.TaskDetailsDesc);
    
                            $("#update").modal('show');
                        });
                    }
                });
            });
    
        </script>


    Here is the Event when somebody press the update details button.

    <script>
            $(function () {
                $("#UpdateDetails").click(function (e) {
                     $.ajax(
                                {
                                    type: "POST",
                                    url: "@Url.Page("/TaskDetails")?handler=UpdateDetail",
                                    data: $('#updatedetail').serialize(),
                                    headers: {
                                        RequestVerificationToken: $('input:hidden[name="__RequestVerificationToken"]').val()
                                    },
                                    success: function (data) {
                                        if (data) {
                                            window.location.href = '@Url.Page("TaskDetails", new { id= @Model.taskDetails.TaskID }  )';
                                        }
                                        else {
                                            window.location.href = '@Url.Page("TaskDetails", new { id= @Model.taskDetails.TaskID }  )';
                                        }
                                    },
                                    error: function (xhr, textStatus, errorThrown) {
                                        alert(errorThrown);
                                    }
                                    });
                     });
                });
        </script>

    Now the problem is the Jquery AJAX does fire the custom handler UpdateDetail. But I am unable to receive the submitted form values. Can Anyone tell me what I am doing wrong?

    Here it  code behind file.

      public JsonResult OnPostUpdateDetail()
            {
                try
                {
                    TaskBO task = new TaskBO();
    
                    var t = Convert.ToInt32(Request.Form["TaskDetailsId"]);
    
                    TaskDetailsViewModel details = new TaskDetailsViewModel()
                    {
                        TimeLineDetails = new TimeLineDetails
                        {
                            TaskDetailsID = Convert.ToInt32(Request.Form["TaskDetailsId"]),
                            IncidentDate = Convert.ToDateTime(Request.Form["IncidentDate"]),
                            TaskDetailsName = Request.Form["TaskDetailsName"],
                            TaskDetailsDesc = Request.Form["TaskDetailsDesc"]
                        }
                    };
                    //task.AddTaskDetails(details);
                    return new JsonResult(new { data = true });
                }
                catch (Exception)
                {
    
                    throw;
                }
            }

    Tuesday, September 1, 2020 9:31 AM

Answers

  • User475983607 posted

    The code shown does not follow any Razor Pages standards and the code itself contains lot of bugs and design issues.  The current state of the code makes it very difficult to provide accurate assistance.  I took the liberty to simplify the code in order to illustrate how to configure a Razor Page handler and submit a basic jQuery AJAX post.  

    ViewModel

        public class TimelineViewModel
        {
            public int TaskID { get; set; }
            public int TaskDetailsId { get; set; }
            public TimeLineDetails Details { get; set; }
        }
    
        public class TimeLineDetails
        {
            public int TaskDetailsID { get; set; }
            public DateTime IncidentDate { get; set; }
            public string TaskDetailsName { get; set; }
            public string TaskDetailsDesc { get; set; }
        }

    Razor Page markup

    @page "{handler?}"
    @model RazorDemo.Pages.ajax.AjaxPostExModel
    @{
    }
    <form method="post" id="updatedetail">
        <div class="modal-body" >
            <input type="hidden" class="form-control" id="TaskID" name="TaskID" value="111">
            <input type="hidden" class="form-control" id="TaskDetailsId" name="TaskDetailsId" value="123">
            <div class="form-group">
                <label for="IncidentDate" class="col-form-label"> </label>
                <input type="date" class="form-control" id="IncidentDate" name="Details.IncidentDate" value="2020-09-01">
            </div>
            <div class="form-group">
                <label for="TaskDetailsName" class="col-form-label"> </label>
                <input type="text" class="form-control" id="TaskDetailsName" name="Details.TaskDetailsName" value="Hello World">
            </div>
            <div class="form-group">
                <label for="TaskDetailsDesc" class="col-form-label"></label>
                <textarea class="form-control" id="TaskDetailsDesc" name="Details.TaskDetailsDesc">Description Example</textarea>
            </div>
        </div>
        <div class="modal-footer">
            <button type="button" class="btn btn-secondary" data-dismiss="modal">Cancel</button>
            <button id="UpdateDetails" type="button" class="btn btn-primary">Submit</button>
        </div>
    </form>
    
    
    @section Scripts
    {
        <script>
            $('#UpdateDetails').click(function () {
                $.ajax(
                    {
                        type: "post",
                        url: "/ajax/ajaxpostex/detail",
                        data: $('#updatedetail').serialize(),
                        success: function (data) {
                            console.log(data);
                        },
                        error: function (xhr, textStatus, errorThrown) {
                            console.log(errorThrown);
                        }
                    });
            });       
        </script>
    
    }
    

    Code behind

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Threading.Tasks;
    using Microsoft.AspNetCore.Mvc;
    using Microsoft.AspNetCore.Mvc.RazorPages;
    using RazorDemo.Models;
    
    namespace RazorDemo.Pages.ajax
    {
        public class AjaxPostExModel : PageModel
        {
            public void OnGet()
            {
            }
    
            public IActionResult OnGetDetail()
            {
                TimelineViewModel model = new TimelineViewModel()
                {
                    TaskID = 1,
                    TaskDetailsId = 2,
                    Details = new TimeLineDetails()
                    {
                        IncidentDate = DateTime.Now,
                        TaskDetailsDesc = "Description",
                        TaskDetailsID = 3,
                        TaskDetailsName = "Detail Name"
                    }
                };
                return new JsonResult(model);
            }
    
            public IActionResult OnPostDetail(TimelineViewModel model)
            {
                return new JsonResult(model);
            }
    
        }
    }
    

    IMHO, the main bug in your code is inputs do not have names.  The serialize() function returns nothing because there are no input names.  Take note of the naming convention illustrated in the markup above.  Dot notation is used when referencing complex ViewModel properties just like C#. 

    Other bugs include the form selector is incorrect; you're not serializing the form.  There's no need for the antiforgery token header because the form contains the antiforgery token.

    Some of the design bugs include not using model binding and doing a JavaScript redirect in the AJAX success handler.  It makes little sense to write AJAX code when a regular form post does the same thing with less code.  There are other issues with the code that I did mention.   I feel you should spend quality time learning Razor Page and HTTP fundamentals.  The following blog is a great resource. https://www.learnrazorpages.com/

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Tuesday, September 1, 2020 1:35 PM