gpt4 book ai didi

javascript - 在 ASP.NET MVC 中使用 Javascript (jQuery) 显示请求结果

转载 作者:行者123 更新时间:2023-12-01 02:04:08 25 4
gpt4 key购买 nike

我有一个 ASP.NET MVC 项目,目前我正在使用 ViewData["ResultMessage"]显示表单的结果(在用户提交并刷新页面后完成)。

我想在他点击提交后立即执行此操作(而不刷新页面)。所以我必须使用 Javascript,这是我刚接触过的。没有任何经验。

我的表单是这样的:

            <form id="contactForm" method="post" action="..">
<div class="field half first">
<label for="Name">Name</label>
<input type="text" name="Name" id="Name" placeholder="Your name" required />
</div>
<div class="field half">
<label for="Email">Email</label>
<input type="email" name="Email" id="Email" placeholder="Your email" required />
</div>
<div class="field">
<label for="Message">Message</label>
<textarea name="Message" id="Message" rows="5" placeholder="Your message" required minlength="20"></textarea>
</div>

<input type="submit" value="Send Message" />
<p>@ViewData["ContactActionResult"]</p>

</form>

您可以看到使用 Razor 显示结果 ViewData 。现在我想做到不刷新页面,顺便学习一下JS。

到目前为止我已经尝试过:

$(function () {
$("button").click(function (e) {
e.preventDefault()
$.ajax({
type: "POST",
url: "/Receiver",
data: car,
datatype: "html",
success: function (data) {
alert("Congratulations, it worked!");
$('#contactForm').html(data);
},
error: function(data) {
alert("Failed.");
}
});
});
});

但我不确定我是否做错了什么或者只是没有正确实现。我里面有上面的函数 <script> here </script>在我的 HTML 页面中。当我单击表单上的提交按钮时,没有任何反应。

最佳答案

如果是ajax调用,最好返回JSON响应。您可以使用 Request.IsAjaxRequest()判断请求是普通形式请求还是ajax调用。

您还应该考虑使用 PRG 模式。成功保存后,您应该重定向到可以渲染 View 的 GET 操作,而不是使用 viewbag 消息返回到同一 View 。如果您想将一些消息传递给新 View /操作,请使用 TempData而不是ViewData .

[HttpPost]
public ActionResult Receiver(string name, string Email)
{
// Your existing code to save
if(Request.IsAjaxRequest())
{
return Json(new { status = "success", message = "Created successfully" });
}
// Normal form submit. So let's follow PRG pattern
TempData["ResultMessage"] = "Created successfully";
return RedirectToAction("Index");
}

您还可以输入 try/catch并针对错误用例返回这样的 json

return Json(new { status = "error", message = "some serious error" });

在索引操作/ View 中,您可以阅读 TempData["ResultMessage"]并向用户显示。

现在,对于 ajax 用例,在当前 View 中,您可以添加一个 div 来显示消息

<form id="contactForm" method="post" asp-action="Receiver">

<div id="msg"></div>

<div class="field half first">
<label for="Name">Name</label>
<input type="text" name="Name" id="Name" placeholder="Your name" required />
</div>
<div class="field half">
<label for="Email">Email</label>
<input type="email" name="Email" id="Email" required />
</div>
<div class="field">
<label for="Message">Message</label>
<textarea name="Message" id="Message" rows="5"
placeholder="Your message" required minlength="20"></textarea>
</div>

<input type="submit" value="Send Message" />

</form>

现在在你的ajax调用中success回调,检查从服务器返回的 json 响应并显示 message根据需要的属性(property)。如果您将脚本放入 razor View 文件中,请确保将其放入 Scripts 中。部分,以便以正确的顺序对其进行评估(加载 jQuery 后,假设您在布局内调用 RenderSection("scripts") 之前加载 jQuery)

@section Scripts
{
<script>
$(function (){

$("#contactForm").submit(function (e){

e.preventDefault()
$.ajax({
type: "POST",
url: $(this).attr("action"),
data: car,
success: function (data){

if (data.status === "success")
{
$('#msg').html(message);
}
//to do : handle statuss=="error" as needed
},
error: function (data)
{
alert("Failed.");
}
});
});
});

</script>
}

对于asp.net core,可以写IsAjaxRequest方法在你的基本 Controller 中并使用它。 jQuery 将添加 X-Requested-With header 值为 XMLHttpRequest用于您的 ajax 调用。

protected bool IsAjaxRequest()
{
return Request.Headers["X-Requested-With"] == "XMLHttpRequest";
}

关于javascript - 在 ASP.NET MVC 中使用 Javascript (jQuery) 显示请求结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50260167/

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