Search code examples
jqueryasp.net-core-mvcrazor-pagesjquery-ajaxq

URL in razor pages dosen't send data to another page


I'm using Razor Pages and I have two pages CreateModel and EditModel, in CreateModel there is OnGetSubGroups handler:

public class CreateModel : PageModel    
 {
  //Dependency Injection is here

  public IActionResult OnGetSubGroups(int subId)
  {
   SubOptions = courseService.CourseSubGroups(subId);
   return new JsonResult(SubOptions);
   }
 }

now the problem is when i want to pass data using JQuery Ajax in Edit.cshtml to OnGetSubGroups URL doesn't work:

$('#Course_GroupId').on('change', function (e) {
 var optionSelected = $("option:selected", this);
 var valueSelected = this.value;
 $.ajax({
   type: "Get",                
    data: {
    subId: valueSelected,                                           
    },          
    url: "/Create?handler=SubGroups",
    contentType: "application/json; charset=utf-8",
    dataType: "json"
});

i've used breakpoint and url dosen't work. where is the problem?


Solution

  • For routing from Edit to Create, you could not use the URL "/Create?handler=SubGroups" which will generate URL like https://localhost:44389/Create?handler=SubGroups&subId=5 and ignore the PageFolder. I assume CreateModel is not in the root folder Pages. If so, you should not combine URL with "/Create?handler=SubGroups".

    I suggest you try code below:

    <script type="text/javascript">
        $(document).ready(function () {
            $.ajax({
                type: "Get",
                data: {
                    subId: 5,
                },
                url:"@Url.Page("Create", "SubGroups")",
                contentType: "application/json; charset=utf-8",
                dataType: "json"
            });
        });
    </script>