gpt4 book ai didi

How to make my Ajax method to call a method from controller(如何使我的AJAX方法从控制器调用方法)

转载 作者:bug小助手 更新时间:2023-10-28 10:13:05 25 4
gpt4 key购买 nike



I have a .NET 6 project where I have a service sending an email and return a bool on success. I have a controller calling that method and return JSON (value success). I also have a view where the form is and where I have my Ajax method to call the method from the controller.

我有一个.NET6项目,在这个项目中,我有一个发送电子邮件并在成功时返回bool的服务。我有一个控制器调用该方法并返回JSON(值Success)。我还有一个视图,窗体在哪里,我的AJAX方法在哪里,以便从控制器调用该方法。


The issue is, when I click on the submit button to submit my form I cannot reach the break point on the method in the controller, so I think that the Ajax method is not calling properly. But the page just reloads.

问题是,当我单击Submit按钮提交表单时,我无法到达控制器中方法的断点,所以我认为AJAX方法没有正确调用。但页面只是重新加载。


Controller Method:

控制器方法:


[HttpPost]
public async Task<IActionResult> PreInscription([FromBody]
PreInscription preInscription){

var inscriptionService =
serviceProvider.GetRequiredService<IInscriptionService>();

if (ModelState.IsValid)
{
var isSend = await
inscriptionService.SendEmailPreInscription(preInscription);

if (isSend)
return Json(new { response = "success" });
}
return Json(new { response = "failed" });
}

View:

观点:


<script src="http://ajax.googleapis.com/ajax/libs/jquery/3.6.4/jquery.min.js"></script>

<script>

function runMethod(){
$.ajax({
url: '@Url.ActionLink("PreInscription", "Inscription")',
type: 'POST',
dataType: 'Json',
async: true,
contentType: "application/json; charset=utf-8",
success: function (response) {
alert(response);
}
});
}

$(document).ready(function () {

$('form').submit(function () {
runMethod();
});

});
</script>


<form asp-action="">
<button id="submitButton" class="btn btn-large btn-theme margintop10"
type="submit">Envoyer</button>
</form>

更多回答
优秀答案推荐

It looks like there are a few issues in your code. Let's go through them step by step and correct them:

看起来您的代码中有一些问题。让我们一步一步地看一遍,并更正它们:


Controller Method Parameters:
Your controller method PreInscription takes a parameter of type PreInscription, but your AJAX call doesn't include any data in the request body. You should pass the data from your form to the server. You can use serialize() to do this.

控制器方法参数:您的控制器方法PreIncription接受一个PreIncription类型的参数,但是您的AJAX调用不在请求体中包含任何数据。您应该将数据从表单传递到服务器。您可以使用Serialize()来实现这一点。


Prevent Default Form Submission:
To prevent the form from being submitted traditionally, you should use event.preventDefault() in your submit event handler.

防止默认表单提交:要防止表单按传统方式提交,您应该在提交事件处理程序中使用Event.PrevenentDefault()。


Alert Display: When displaying the JSON response, you should specify response.response since your JSON response contains a property named "response."

警报显示:在显示JSON响应时,您应该指定Response.Response,因为您的JSON响应包含一个名为“Response”的属性。


Here's the corrected code:

以下是更正后的代码:


Controller Method:

控制器方法:


[HttpPost]
public async Task<IActionResult> PreInscription([FromBody] PreInscription preInscription)
{
var inscriptionService = serviceProvider.GetRequiredService<IInscriptionService>();

if (ModelState.IsValid)
{
var isSend = await inscriptionService.SendEmailPreInscription(preInscription);

if (isSend)
return Json(new { response = "success" });
}
return Json(new { response = "failed" });
}

View:

观点:


<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.4/jquery.min.js"></script>

<script>
function runMethod() {
$.ajax({
url: '@Url.Action("PreInscription", "YourControllerName")',
type: 'POST',
dataType: 'json',
contentType: "application/json; charset=utf-8",
data: JSON.stringify({ /* Your form data here */ }), // Pass form data
success: function (response) {
alert(response.response); // Use response.response to access the JSON property
}
});
}

$(document).ready(function () {
$('form').submit(function (event) {
event.preventDefault(); // Prevent default form submission
runMethod();
});
});
</script>

<form asp-controller="YourControllerName" asp-action="PreInscription">
<!-- Your form fields here -->
<button id="submitButton" class="btn btn-large btn-theme margintop10" type="submit">Envoyer</button>
</form>

Replace "YourControllerName" with the actual name of your controller where the PreInscription action is located.

将“YourControllerName”替换为PreIncription操作所在的控制器的实际名称。


In the data field of your AJAX call, you should pass the actual form data that you want to submit to the server. You can use jQuery's serialize() function to serialize the form data. Make sure your form fields have proper name attributes that match the properties of the PreInscription model.

在您的AJAX调用的数据字段中,您应该传递要提交给服务器的实际表单数据。您可以使用jQuery的Serialize()函数来序列化表单数据。确保您的表单域具有与PreIncription模型的属性匹配的正确的名称属性。


With these changes, your form should now submit the data via AJAX to the controller's PreInscription method, and you should be able to reach the breakpoint in your controller.

有了这些更改,您的表单现在应该通过AJAX将数据提交给控制器的PreIncription方法,并且您应该能够到达控制器中的断点。


更多回答

This resolved my issue. Thank you very much for the detailed explanation.

这解决了我的问题。非常感谢您的详细解释。

@Adriel: ChatGPT (or similar) does get lucky from time to time (usually not).

@Adriel:ChatGPT(或类似的)确实偶尔会有运气(通常不会)。

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com