gpt4 book ai didi

c# - PartialViewResult Form 不会清除 ajax 结果上的值 - ASP.NET Core Razor c#

转载 作者:太空宇宙 更新时间:2023-11-03 12:07:04 24 4
gpt4 key购买 nike

我有一个用 razor asp.net 和 c# 编写的简单联系消息表单。每当提交表单时,我都能毫无问题地呈现服务器响应,但出于某种原因,所有输入字段都保持相同的值。

这是部分 View :

   @using PublicWebsite.Models.Contact;

@model ContactFormViewModel

<form role="form" id="contactForm" data-toggle="validator" method="post" asp-controller="Contact" asp-action="SubmitMessage">
@if (!string.IsNullOrWhiteSpace(Model.ServerResponse))
{
<div class="form-group">
<div class="row">
<div class="col-md-12">
<div class="alert @(Model.ServerResponseSuccess ? "alert-success" : "alert-danger")" role="alert">
@Model.ServerResponse
</div>
</div>
</div>
</div>
}

<div class="form-group">
<div class="row">
<div class="col-md-12">
<div class="form-group">
<div class="prepend-icon">
<input type="text" asp-for="@Model.Name" name="Name" class="form-control input-lg" placeholder="Your Full Name" maxlength="50" required>
<i class="nc-icon-outline users_single-03"></i>
</div>
<div class="help-block with-errors"></div>
</div>
</div>
</div>
</div>
<div class="form-group">
<div class="row">
<div class="col-md-6">
<div class="form-group">
<div class="prepend-icon">
<input type="email" asp-for="@Model.Email" name="Email" class="form-control input-lg" placeholder="Email" maxlength="200" required />
<i class="nc-icon-outline ui-1_email-85"></i>
</div>
<div class="help-block with-errors"></div>
</div>
</div>
<div class="col-md-6">
<div class="form-group">
<div class="prepend-icon">
<input type="tel" asp-for="@Model.Phone" name="Phone" class="form-control input-lg" placeholder="Phone Number" maxlength="25" required>
<i class="nc-icon-outline ui-2_phone"></i>
</div>
<div class="help-block with-errors"></div>
</div>
</div>
</div>
</div>
<div class="form-group">
<div class="row">
<div class="col-md-6">
<select class="form-control" asp-for="@Model.ContactReason" name="ContactReason" data-container-class="input-lg" required style="height:46px !important">
<option value="">Choose a Reason</option>
<option value="Home Remediation">Home Remediation</option>
<option value="Commercial Remediation">Commercial Remediation</option>
<option value="Employment Opportunities">Inquire about employment oppotunities</option>
<option value="Other">Other</option>
</select>
</div>
<div class="col-md-6">

</div>
</div>
</div>
<div class="form-group">
<textarea asp-for="@Model.Message" class="form-control" rows="10" name="Message" placeholder="Message" required></textarea>
<div class="help-block with-errors"></div>
</div>
<div class="form-group">
<div class="g-recaptcha" data-sitekey="mysitekeyishere"></div>
<input type="hidden" name="RecaptchaResponse" value="" />
</div>
<button type="submit" id="form-submit" class="btn btn-primary btn-lg icon-left-effect"><i class="nc-icon-outline ui-1_email-85"></i><span>Send message</span></button>
<div id="msgSubmit" class="hidden"></div>
</form>

下面是 View 模型:

using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Threading.Tasks;

namespace PublicWebsite.Models.Contact
{
public class ContactFormViewModel
{
[StringLength(50)]
public string Name { get; set; } = "";

[StringLength(200)]
public string Email { get; set; } = "";

[StringLength(25)]
public string Phone { get; set; } = "";

[StringLength(50)]
public string ContactReason { get; set; } = "";

public string Message { get; set; } = "";

[StringLength(250)]
public string ServerResponse { get; set; } = "";

public bool ServerResponseSuccess { get; set; } = false;
}
}

在联系人的联系人索引 CSHTML 页面内,我毫无问题地呈现了部分 View 。

@section Scripts {
<script src="@validatorPath"></script>

<script type="text/javascript">
$(function () {
$(document).on('submit', '#contactForm', function (e) {
$form = $(this);
$url = $form.attr('action');
$.ajax({
type: "POST",
url: $url,
data: $form.serialize(), // serializes the form's elements.
success: function (data) {
loadFormData(data); //This works
resetCaptcha();
},
error: function (data) {
alert(data);
}
});

e.preventDefault(); // avoid to execute the actual submit of the form.
});

function loadFormData(data) {
$formContainer = $('.contact-form-container');
$formContainer.empty();
$formContainer.html(data);
console.log(data); //This reports back the same results
}

function resetCaptcha() {
//reset captcha
$('.g-recaptcha').empty();
$.getScript('@recaptchaUrl');
}
});
</script>
}

<div class="col-md-7 contact-form-container">
@{ await Html.RenderPartialAsync("_ContactForm", new ContactFormViewModel()); }
</div>

一切都正确呈现。如下面的屏幕截图所示。

This is what renders on the page initially

填写项目后,将调用以下 sendmessage 函数,如上面的脚本部分所示。

 [HttpPost]
public async Task<IActionResult> SubmitMessage(ContactFormViewModel contactForm)
{
var captchaResponse = Request.Form["g-recaptcha-response"].ToString();

if (string.IsNullOrWhiteSpace(captchaResponse))
{
contactForm.ServerResponse = _errorCaptchaMessageBlank;
}
else
{
if (await ValidCaptcha(captchaResponse))
{
try
{
await SendCustomerMessage(contactForm);

var customerName = contactForm.Name;

//This works
contactForm = new ContactFormViewModel
{
ServerResponse = String.Format(_successfulSendMessage, customerName.Split(' ')[0]),
ServerResponseSuccess = true
};
}
catch
{
contactForm.ServerResponse = _errorCaptchaMessageInvalid;
}
}
else
{
contactForm.ServerResponse = _errorCaptchaMessageInvalid;
}
}

//This works and I get the response back on the front end
return PartialView("_ContactForm", contactForm);
}

您甚至可以在成功尝试访问服务器时看到消息错误(即 HTML 中显示的服务器响应)并且它会保留用户的信息,因此他们不必重新输入数据如下图所示。

Server Response error that appears for re-captcha error

现在成功了,请注意在上面的代码中我创建了一个新的联系表单,其中包含已清除的值和一条成功消息。但是,相同的信息会像下面这样填写。我希望清除联系表。

enter image description here

我什至尝试过返回一个全新的 View 模型,但仍然有同样的问题,即所有数据几乎都被缓存了。在我来自服务器的 console.log 响应中,我得到了一个部分 View 结果,其中预填充了值,所以我知道这不是浏览器问题。即使当我调试 CSHTML 页面时,我也只看到服务器响应和 success = true,所有其他字段都是空白的。

如果您能帮助弄清楚为什么服务器仍然返回带有填充数据的部分 View 结果,我们将不胜感激。

partial view result response from server

最佳答案

您可以将其添加到您的成功回调函数中:

$('#contactForm').find('input[type=text], textarea, select').val('');

它基本上找到表单中的所有输入字段并清除它们的值。

关于c# - PartialViewResult Form 不会清除 ajax 结果上的值 - ASP.NET Core Razor c#,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54393113/

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