我有联系表格,以便用户与我联系。它是用asp.net mvc编写的,但问题是在提交后没有填写任何文本框,就没有在texbox上验证。
这是我的表格:
@using (Html.BeginForm("contact","Home", FormMethod.Post, new { @enctype = "multipart/form-data" }))
{
@Html.AntiForgeryToken()
@Html.ValidationSummary(true)
<section id="contact" class="text-center">
<div class="container">
<div class="row">
<div class="col-md-12 wow fadeInDown" data-wow-delay="2000">
<h3>CONTACT Microrout.nl</h3>
</div>
<div class="col-md-2"></div>
<div class="col-md-8">
Microrout.nl
<br />frederik hendriklaan 253-b
<br />Den Haag
<br />0641697144
</div>
<div class="col-md-2"></div>
<hr />
<div class="form-group">
<div class="col-md-10">
@Html.TextBoxFor(m => m.FromName, new {placeholder = "Your Name", @class = "form-control" })
@Html.ValidationMessageFor(m => m.FromName)
</div>
</div>
<div class="form-group">
<div class="col-md-10">
@Html.TextBoxFor(m => m.subject, new {placeholder = "Subject of message", @class = "form-control" })
@Html.ValidationMessageFor(m => m.subject)
</div>
</div>
<div class="form-group">
<div class="col-md-10">
@Html.TextBoxFor(m => m.FromEmail, new {placeholder ="Your email", @class = "form-control" })
@Html.ValidationMessageFor(m => m.FromEmail)
</div>
</div>
<div class="form-group">
<div class="col-md-10">
@Html.TextAreaFor(m => m.Message, new {placeholder = "Your message", @class = "form-control" })
@Html.ValidationMessageFor(m => m.Message)
</div>
</div>
<div class="form-group">
<div class="col-md-3">
<input type="submit" value="SHOOT MESSAGE" class="form-control">
</div>
</div>
</div>
</div>
@*<div class="google_map">
<div id="map-canvas"></div>
</div>*@
</section>
}
</section>
这是我在控制器中的方法:
public ActionResult Contact()
{
ViewBag.Message = "Your contact page.";
return View();
}
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<ActionResult> Contact(EmailFormModel model)
{
string message2 = "There are a few errors";
if (ModelState.IsValid)
{
var body = "<p>Email From: {0} ({1})</p><p>Message:</p><p>{2}</p>";
var message = new MailMessage();
message.To.Add(new MailAddress("nengelen@online.nl")); //replace with valid value
message.Subject = model.subject;
message.Body = string.Format(body, model.FromName, model.FromEmail, model.Message);
message.IsBodyHtml = true;
using (var smtp = new SmtpClient())
{
await smtp.SendMailAsync(message);
}
message2 = "Thanks! We'll get back to you soon.";
//Response.Write("Error sending email: " + error.Message + "<br /> StackTrace: " + error.StackTrace);
//ViewBag.Message = "Thank you for contact us";
//return new RedirectToActionAnchor("Contact", "", "#contact");
}
if (Request.IsAjaxRequest())
{
return new JsonResult { Data = new { success = true, message = message2 } };
}
TempData["Message"] = message2;
return new RedirectResult(Url.Action("") + "#contact");
}
我现在就这样:
public ActionResult Contact()
{
EmailFormModel model = TempData["EmailFormModel"] as EmailFormModel;
ViewBag.Message = "Your contact page.";
return View();
}
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<ActionResult> Contact(EmailFormModel model)
{
TempData["EmailFormModel"] = model;
string message2 = "There are a few errors";
if (ModelState.IsValid)
{
var body = "<p>Email From: {0} ({1})</p><p>Message:</p><p>{2}</p>";
var message = new MailMessage();
message.To.Add(new MailAddress("nengelen@online.nl")); //replace with valid value
message.Subject = model.subject;
message.Body = string.Format(body, model.FromName, model.FromEmail, model.Message);
message.IsBodyHtml = true;
using (var smtp = new SmtpClient())
{
await smtp.SendMailAsync(message);
}
return new RedirectResult(Url.Action("") + "#contact");
}
if (Request.IsAjaxRequest())
{
return new JsonResult { Data = new { succes = true, message = message2 } };
}
TempData["Message"] = message2;
return View(model);
}
这是模型:
public class EmailFormModel
{
[Required, Display(Name="subject")]
public string subject { get; set; }
[Required, Display(Name = "Your name")]
public string FromName { get; set; }
[Required, Display(Name = "Your email"), EmailAddress]
public string FromEmail { get; set; }
[Required]
public string Message { get; set; }
}
我正在使用smoothScroll导航,如下所示:
<div class="collapse navbar-collapse">
<ul class="nav navbar-nav navbar-right">
<li><a href="#home" class="smoothScroll">HOME</a></li>
<li><a href="#about" class="smoothScroll">STUDIO</a></li>
<li><a href="#team" class="smoothScroll">TEAM</a></li>
<li><a href="#service" class="smoothScroll">SERVICES</a></li>
<li><a href="#work" class="smoothScroll">WORK</a></li>
<li><a href="#pricing" class="smoothScroll">PRICING</a></li>
<li><a href="#contact" class="smoothScroll">CONTACT</a></li>
@*<li>@Html.ActionLink("Contact", "Contact", "Home")
</li>*@
</ul>
</div>
所以在导航中它会跳转到索引页面的正确区域
我现在就这样:
[HttpGet]
public ActionResult Contact(string uniqueUri)
{
EmailFormModel model = TempData["EmailFormModel"] as EmailFormModel;
//ViewBag.Message = "Your contact page.";
return View(model);
}
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<ActionResult> Contact(EmailFormModel model)
{
TempData["EmailFormModel"] = model;
string message2 = "There are a few errors";
if (ModelState.IsValid)
{
var body = "<p>Email From: {0} ({1})</p><p>Message:</p><p>{2}</p>";
var message = new MailMessage();
message.To.Add(new MailAddress("nengelen@online.nl")); //replace with valid value
message.Subject = model.subject;
message.Body = string.Format(body, model.FromName, model.FromEmail, model.Message);
message.IsBodyHtml = true;
using (var smtp = new SmtpClient())
{
await smtp.SendMailAsync(message);
}
return new RedirectResult(Url.Action("") + "#contact");
}
else
{
ModelState.AddModelError("ReviewErrors", "some error occured");
//return RedirectToAction("Create", new { uniqueUri = Request.RequestContext.RouteData.Values["uniqueUri"] });
return new RedirectResult(Url.Action("") + "#contact");
}
}
我现在就这样:
public ActionResult Contact()
{
EmailFormModel model = TempData["EmailFormModel"] == null ? new EmailFormModel() : (EmailFormModel)TempData["EmailFormModel"];
ViewBag.Message = "Your contact page.";
return View(model);
}
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<ActionResult> Contact(EmailFormModel model)
{
TempData["EmailFormModel"] = model;
string message2 = "There are a few errors";
if (ModelState.IsValid)
{
var body = "<p>Email From: {0} ({1})</p><p>Message:</p><p>{2}</p>";
var message = new MailMessage();
message.To.Add(new MailAddress("nengelen@online.nl")); //replace with valid value
message.Subject = model.subject;
message.Body = string.Format(body, model.FromName, model.FromEmail, model.Message);
message.IsBodyHtml = true;
using (var smtp = new SmtpClient())
{
await smtp.SendMailAsync(message);
}
return new RedirectResult(Url.Action("") + "#contact");
}
else
{
ModelState.AddModelError("ReviewErrors", "some error occured");
//return RedirectToAction("Create", new { uniqueUri = Request.RequestContext.RouteData.Values["uniqueUri"] });
return new RedirectResult(Url.Action("") + "#contact");
}
}
并且在调试模式下,如果我没有填写字段,它就会出现:
else
{
ModelState.AddModelError("ReviewErrors", "some error occured");
//return RedirectToAction("Create", new { uniqueUri = Request.RequestContext.RouteData.Values["uniqueUri"] });
return new RedirectResult(Url.Action("") + "#contact");
}
但验证不可见
谢谢大家的努力。但我刚刚建立了一个新的联系页面,现在它的工作正常。只需要弄清楚,导航中的正确链接,但我刚刚提出了新的问题。我只是将DaWood标记为最佳解决方案,因为你可以&#39;将多个标记作为answare。
谢谢大家!!
答案 0 :(得分:2)
你错过了:
if (!ModelState.IsValid)
{
return View(model);
}
您需要使用问题呈现视图。然后,框架将获取验证错误并显示它们。
答案 1 :(得分:1)
之后
public String listener(Socket x) throws IOException{
try {
Log.d("Listener","Started");
String inp;
BufferedReader in = new BufferedReader(new InputStreamReader(x.getInputStream()));
inp = in.readLine();
Log.d("Listener","Ended");
return inp;
} catch (UnknownHostException e1) {
e1.printStackTrace();
return "ERROR";
} catch (IOException e1) {
e1.printStackTrace();
return "ERROR";
}
}`
您正在致电:
if(ModelState.IsValid)
刷新页面并清除ModelState。
如果,您需要调用RedirectResult,请点击此链接
ASP.NET MVC - How to Preserve ModelState Errors Across RedirectToAction?
或强>
您需要返回 return new RedirectResult(Url.Action("") + "#contact");
才能获得验证错误。
View(model)
修改强>
if(ModelState.IsValid)
{
// ...........Other Code:
return new RedirectResult(Url.Action("") + "#contact");
}
if (Request.IsAjaxRequest())
{
return new JsonResult { Data = new { success = true, message = message2 } };
}
TempData["Message"] = message2;
return View(model);
答案 2 :(得分:0)
当模型状态无效时,您需要添加else。并在if内移动你的返回值,当模型状态有效时,你返回模型的正检查。当模型状态无效时,将返回视图,这将保留模型状态数据。
if (ModelState.IsValid)
{
var body = "<p>Email From: {0} ({1})</p><p>Message:</p><p>{2}</p>";
var message = new MailMessage();
message.To.Add(new MailAddress("nengelen@online.nl")); //replace with valid value
message.Subject = model.subject;
message.Body = string.Format(body, model.FromName, model.FromEmail, model.Message);
message.IsBodyHtml = true;
using (var smtp = new SmtpClient())
{
await smtp.SendMailAsync(message);
}
message2 = "Thanks! We'll get back to you soon.";
//Response.Write("Error sending email: " + error.Message + "<br /> StackTrace: " + error.StackTrace);
//ViewBag.Message = "Thank you for contact us";
//return new RedirectToActionAnchor("Contact", "", "#contact");
TempData["Message"] = message2;
if (Request.IsAjaxRequest())
{
return new JsonResult { Data = new { success = true, message = message2 } };
}
return new RedirectResult(Url.Action("") + "#contact");
}
else
{
return View();
}
此外,如果模型无效,您可能希望启用内置客户端验证以保存到服务器的往返。