【发布时间】:2016-04-08 15:37:20
【问题描述】:
我有一个问题,即我第一次提交时正确地重新加载了 AJAX 联系表单并带有验证警告,但是如果我随后再次提交表单而不修复验证问题,它只会加载联系表单部分视图,没有其他内容.如果我在验证提交失败后修复验证问题并提交表单,它会发送但通常在页面内加载的部分“发送”视图会自行加载为自己的页面。
这是我的表格(缩写):
@model international_mvc.Models.contactform
<script type="text/javascript" src="@Url.Content("/scripts/contactform.js")"></script>
<script src="https://www.google.com/recaptcha/api.js" async defer></script>
<div id="form_container" class="highlight_box contact_box">
@using (Ajax.BeginForm("FormSubmit", "Home", new AjaxOptions
{
HttpMethod = "POST",
UpdateTargetId = "cont_form"
}, new { id = "cont_form" }))
{
@Html.ValidationSummary(true)
@Html.AntiForgeryToken()
<div class="form_col_l">
<p class="form_title">
@Html.LabelFor(model => model.FirstName, "Name")@Html.ValidationMessageFor(model => model.FirstName, null, new { @class = "errortext" })
</p>
<div class="resize_input">
@Html.EditorFor(model => model.FirstName, new { htmlAttributes = new { placeholder = "First Name" } })
</div>
<div class="rcp_cont_right">
<p style="font-size:18px; color:red;">@ViewBag.Message</p>
</div>
<div class="buttoncontainer">
<button class="button_form_send" name="btn" id="btn" type="submit">Send to OnLineTraining</button>
<button class="button_form_clear" type="reset">Clear form</button>
</div> }
这是与表单提交相关的控制器部分:
public ActionResult sent()
{
return PartialView();
}
[HttpPost]
[ValidateAntiForgeryToken]
public async System.Threading.Tasks.Task<ActionResult> FormSubmit(contactform model)
{
var response = Request["g-recaptcha-response"];
string secretKey = "akey";
var client = new WebClient();
var result = client.DownloadString(string.Format("https://www.google.com/recaptcha/api/siteverify?secret={0}&response={1}", secretKey, response));
var obj = JObject.Parse(result);
var status = (bool)obj.SelectToken("success");
ViewBag.Message = status ? "Google reCaptcha validation success" : "Please click on the recaptcha";
if (ModelState.IsValid && status)
{
try
{
var body = "<p>Email From: {0} ({1})</p><p>Message:</p><p>{2}</p>";
var message = new System.Net.Mail.MailMessage();
message.To.Add(new MailAddress("anemail"));
message.Subject = "Contact Us";
message.Body = string.Format(body, model.FirstName, model.LastName, model.Role, model.Location, model.Email, model.forg, model.orgname, model.COM, model.commissioninginfo, model.addinfo, model.phone);
message.IsBodyHtml = true;
using (var smtp = new SmtpClient())
{
await smtp.SendMailAsync(message);
return PartialView("_sent", model);
}
}
catch (Exception)
{
return View("Error");
}
}
else
{
return PartialView("_contactform", model);
}
}
谁能向我解释我做错了什么,当用户第一次未能正确填写表单时,如何让表单继续在同一页面上返回相同的部分视图?
我应该提到上面的表格是另一个页面的一部分,看起来像这样:
<h2>Contact us</h2>
@Html.Partial("_contactform")
谢谢
【问题讨论】:
标签: jquery ajax asp.net-mvc forms