大家好,我已经创建了一个实体,并且我使用了一个模型,#34;客户"现在我尝试通过视图中输入的字段发送电子邮件 这就是我所拥有的,出于安全考虑,我只使用了一个字段进行测试,端口号,主机等是随机文本
观点:
@model _2.Models.Client
@using (Html.BeginForm())
{
@Html.AntiForgeryToken()
@Html.ValidationSummary(true)
<fieldset>
<legend>Client</legend>
<div class="editor-label">
@Html.LabelFor(model => model.Title)
</div>
<div class="editor-field">
@Html.EditorFor(model => model.Title)
@Html.ValidationMessageFor(model => model.Title)
</div>
<div class="editor-label">
@Html.LabelFor(model => model.Initials)
</div>
<div class="editor-field">
@Html.EditorFor(model => model.Initials)
@Html.ValidationMessageFor(model => model.Initials)
</div>
<div class="editor-label">
@Html.LabelFor(model => model.FirstName)
</div>
<div class="editor-field">
@Html.EditorFor(model => model.FirstName)
@Html.ValidationMessageFor(model => model.FirstName)
</div>
<p>
<input type="submit" value="Create" />
</p>
</fieldset>
}
控制器:
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<ActionResult> Contact(Client model)
{
try
{
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("test.co.za"));
message.To.Add(new MailAddress("test.co.za"));
message.From = new MailAddress("test.co.za");
message.Subject = "Your email subject";
message.Body = string.Format(body, model.Title, model.Initials, model.FirstName);
message.IsBodyHtml = true;
using (var smtp = new SmtpClient())
{
{
smtp.Host = "host";
smtp.Port = port number;
await smtp.SendMailAsync(message);
smtp.Dispose();
return RedirectToAction("Sent");
};
}
}
return View(model);
}
catch (NullReferenceException ex)
{
return Content("Data added successfully" + ex);
}
}
public ActionResult Sent()
{
return View();
}
这是我得到的错误
System.NullReferenceException: Object reference not set to an instance of an object
即使我在字段中输入了文本,它也会取出空值,请帮我解决这个问题,谢谢你的时间 我创建了一个客户端实例,但它只是发送带有正文的空白电子邮件,它没有发送在编辑器字段中输入的值
答案 0 :(得分:0)
控制器:
过去我看到控制器操作返回ActionResult
但从来没有
async Task<ActionResult>
击>
never mind
MVC有时候不喜欢事物的名称,我会尝试命名您传入的客户model
,client
。
HTML:
BeginForm()
也错过了您的操作和控制器,但我确定您已将其排除在外。 调试提示:
Client.Title = "fancy title"
)