Reputation: 31
I am working on an ASP.NET Core 2.1 application. I need to call a named page handler through ajax.
The method works correctly while in debug/release, but fails once it is published to IIS.
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<location path="." inheritInChildApplications="false">
<system.webServer>
<modules runAllManagedModulesForAllRequests="true" />
<handlers>
<add name="aspNetCore" path="*" verb="*" modules="AspNetCoreModule" resourceType="Unspecified" />
</handlers>
<aspNetCore processPath="dotnet" arguments=".\MyApp.dll" stdoutLogEnabled="false" stdoutLogFile=".\logs\stdout" />
</system.webServer>
</location>
</configuration>
This is the handler method, there are similar ones in other pages and none of them is found by the ajax request (but again, this only happens once it is deployed to IIS):
[HttpPost]
public IActionResult OnPostExampleHandler([FromForm]ExampleHandlerModel model)
{
// ...
return new JsonResult(new { data, message });
}
This is the javascript code which is called on submit:
function submitForm()
{
return $.ajax(
{
type: "POST",
url: "/relativeURL/ExampleHandler",
data: $('#ExampleHandlerForm').serialize(),
dataType: "json",
complete: function (res)
{
// do something on completion
}
});
}
And lastly this is the Html/Razor code, I am using the 'form' TagHelper which ensures the AntiForgeryToken is present when the form is serialized:
<form method="post" asp-page-handler="ExampleHandler" id="ExampleHandlerForm">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title">@Model.Details.Description</h5>
<button type="button" class="close" data-dismiss="modal">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body form-row">
@* Input Fields *@
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-dismiss="modal">@Lang.Operations.Close</button>
<button type="button" onclick="submitForm();" class="btn btn-primary">@Lang.Operations.Save</button>
</div>
</div>
</form>
POST http://root:port/relativeURL/ExampleHandler 404 (Not Found)
send @ jquery.min.js:2
ajax @ jquery.min.js:2
submitForm @ VM106:13
onclick @ 5:1
Upvotes: 3
Views: 2854
Reputation: 233
Worked for me.
Example:
url: 'NameOfPageModel?handler=NameOfHandler'
don't forget to remove prefix OnPost and suffix Async(if exist) from handler name.
Upvotes: 3