great help about a very confusing subject, thanks
Calling asp-page handler method from javascript
Hi all,
i am not able to post my question here.
Please find my question in attached file. Anyhelp would be appreciated
Please click here 145155-callingaspmethodjavascript.txt
2 answers
Sort by: Newest
-
-
Zhi Lv - MSFT 32,031 Reputation points Microsoft Vendor
2021-11-01T03:10:37.82+00:00 Hi @Blooming Developer ,
From your code, since you are using the
type="submit"
button, I assume there must have a form, right? After clicking the submit button, it will submit the form by default. In this scenario, if you are using the Ajax method to submit the form, it will submit twice. So, in the submit button click event, to use Ajax method, you must call theevent.preventDefault();
command to prevent the default from submit action. You can refer the following code to use JQuery Ajax method to call the handler method:In the Index page, create a handler method as below:
public class IndexModel : PageModel { private readonly ILogger<IndexModel> _logger; private readonly ICurriculumService _repository; public IndexModel(ILogger<IndexModel> logger, ICurriculumService datatRepository) { _logger = logger; _repository = datatRepository; } public void OnGet() { } public async Task<IActionResult> OnPostSubmitAsync() { return new JsonResult("success"); } }
Then in the Index.cshtml: add a form with javascript:
You can download the
index.cshtml
code from here: 145278-indexcshtml.txtThe result as below:
If you want to redirect to another page after calling the handler, you can use change the request url via the
window. location .href
(please remove the space) in the Ajax success function. Or you can remove the Ajax method, and in the button click event, you can add the custom validation, then based on the result to submit the form (get the form by id, then use thesubmit
method submit the form).Update:
Code like this:
document.getElementById("mainform").submit();
The result as below:
If the answer is the right solution, please click "Accept Answer" and kindly upvote it. If you have extra questions about this answer, please click "Comment".
Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.Best regards,
Dillion