我一直在敲我的头,试图找出这里有什么问题。我是C#的新手,一般来说对MVC来说还算新手。我需要一个简单的电子邮件联系表格,用于我的网站。我不完全确定韵或理由是什么,但控制器将注册表单的所有字段,但跳过smtp.Send(msg);
并跳到catch方法。我试过在[POST]
之后加入[GET]
方法,我读过这篇文章,但仍然没有运气。我有一种感觉,这是与SMTP端口或主机的问题,但我找不到任何文档。联系页面表单抛出错误MVC
此外,我也尝试添加一些按钮功能的片段,但也没有运气。任何帮助都会很棒。
型号
public class ContactModels
{
[Required(ErrorMessage ="Your name is required")]
public string FullName { get; set; }
[Required(ErrorMessage = "Your email is required")]
public string Email { get; set; }
[Required(ErrorMessage = "Your phone number is required")]
public string Phone { get; set; }
[Required(ErrorMessage = "You must type a message")]
public string Comment { get; set; }
}
查看
<div class="col-md-4">
<p><strong>Phone: </strong>586.xxx.xxxx</p>
<p><strong>Email: </strong><a href="mailto:[email protected]">[email protected]</a></p>
<p><strong>Address: </strong>Address Here</p>
<h3>Connect with us through Email </h3>
@using (Html.BeginForm(FormMethod.Post))
{
@Html.ValidationSummary(true)
<div class="row">
@Html.LabelFor(model=>model.FullName, "Name: ")
@Html.EditorFor(model=>model.FullName)
@Html.ValidationMessageFor(model=>model.FullName)
</div>
<div class="row">
@Html.LabelFor(model=>model.Email, "Email: ")
@Html.EditorFor(model=>model.Email)
@Html.ValidationMessageFor(model=>model.Email)
</div>
<div class="row">
@Html.LabelFor(model=>model.Phone, "Phone: ")
@Html.EditorFor(model=>model.Phone)
@Html.ValidationMessageFor(model=>model.Phone)
</div>
<div class="row">
@Html.LabelFor(model=>model.Comment, "Message: ")
@Html.TextAreaFor(model=>model.Comment)
@Html.ValidationMessageFor(model=>model.Comment)
</div>
<div class="row">
<input type="submit" value="Send"/>
<input type="reset" value="Reset"/>
</div>
}
</div>
控制器
public ActionResult Contact()
{
return View();
}
[HttpPost]
public ActionResult Contact(Models.ContactModels c)
{
if (ModelState.IsValid)
{
try
{
MailMessage msg = new MailMessage();
SmtpClient smtp = new SmtpClient();
MailAddress from = new MailAddress(c.Email.ToString());
StringBuilder sb = new StringBuilder();
msg.To.Add("[email protected]");
msg.Subject = "Contact Us";
msg.IsBodyHtml = false;
smtp.Host = "smtp.gmail.com";
smtp.Port = 993;
sb.Append("Name: " + c.FullName);
sb.Append(Environment.NewLine);
sb.Append("Email: " + c.Email);
sb.Append(Environment.NewLine);
sb.Append("Phone: " + c.Phone);
sb.Append(Environment.NewLine);
sb.Append("Comment: " + c.Comment);
sb.Append(Environment.NewLine);
msg.Body = sb.ToString();
smtp.Send(msg);
msg.Dispose();
return View("Success");
}
catch(Exception)
{
return View("Error");
}
}
return View();
}
将'catch(Exception)'变为'catch(Exception ex)',并在那里放置一个断点并检查ex变量以获取有关该错误的更多信息。 – Shyju
@Shyju ex变量读取一个空值 –
catch(Exception ex)中的'ex'变量应该向您显示Exception类型,消息,最重要的是堆栈跟踪,它应该准确地告诉您哪个方法失败。很可能你正在使用具有'null'值的属性之一进行字符串连接。你也应该使用一个使用块或像'SmtpClient'这样的finally块来处理所有的一次性物品。 – Igor