我正在尝试使用ViewModel创建我认为非常简单的表单提交。 我断断续续地工作了一整天,由于某种原因,我不明白为什么当我的应用程序进入我的 HttpPost 操作时,我的 EmailViewModel 是空的。 我收到"发生空引用异常"对象引用未设置为对象的实例"错误。
你能看看我的代码,告诉我我在哪里疯了吗?
这是我的httpPost操作:
[HttpPost]
public ActionResult SendStudentAnEmail(EmailViewModel email)
{
Debug.Write(email.Subject); // First NullReferenceException
Debug.Write(email.Body);
Debug.Write(email.Email);
etc. . .
我的视图模型:
namespace MyApp.ViewModels
{
public class EmailViewModel
{
public string Email { get; set; }
public string Subject { get; set; }
public string Body { get; set; }
}
}
和我的观点:
@model MyApp.ViewModels.EmailViewModel
@{
ViewBag.Title = "SendStudentAnEmail";
}
<h2>SendStudentAnEmail</h2>
<script src="@Url.Content("~/Scripts/jquery.validate.min.js")" type="text/javascript"></script>
<script src="@Url.Content("~/Scripts/jquery.validate.unobtrusive.min.js")" type="text/javascript"></script>
@using (Html.BeginForm()) {
@Html.ValidationSummary(true)
<fieldset>
<legend>EmailViewModel</legend>
<div class="editor-label">
@Html.LabelFor(model => model.Email)
</div>
<div class="editor-field">
@Html.EditorFor(model => model.Email)
@Html.ValidationMessageFor(model => model.Email)
</div>
<div class="editor-label">
@Html.LabelFor(model => model.Subject)
</div>
<div class="editor-field">
@Html.EditorFor(model => model.Subject)
@Html.ValidationMessageFor(model => model.Subject)
</div>
<div class="editor-label">
@Html.LabelFor(model => model.Body)
</div>
<div class="editor-field">
@Html.EditorFor(model => model.Body)
@Html.ValidationMessageFor(model => model.Body)
</div>
<p>
<input type="submit" value="Save" />
</p>
</fieldset>
}
<div>
@Html.ActionLink("Back to List", "Index")
</div>
谢谢。
*更新*
如果我将 HttpPost Action 更改为使用 FormCollection,我可以很好地使用这些值,我甚至可以将 FormCollection 值重新转换为我的 EmailViewModel。 这是为什么呢?
[HttpPost]
public ActionResult SendStudentAnEmail(FormCollection emailFormCollection)
{
Debug.Write(emailFormCollection["email"]);
Debug.Write(emailFormCollection["subject"]);
Debug.Write(emailFormCollection["body"]);
var email = new EmailViewModel
{
Email = emailFormCollection["email"],
Subject = emailFormCollection["subject"],
Body = emailFormCollection["body"]
};
. . . . then the rest of my code works just how I wanted. . .
为什么我必须从 FormCollection 转换到我的 EmailViewModel? 如果我尝试简单地将电子邮件视图模型推送到我的操作中,为什么它不会给我 NullReference 异常?
您的EmailViewModel
类具有一个名为字符串类型Email
的属性。您的控制器操作采用一个名为 email
的参数,类型为 EmailViewModel
。这会混淆默认模型绑定器。因此,重命名视图模型或操作参数中的属性:
[HttpPost]
public ActionResult SendStudentAnEmail(EmailViewModel model)
{
Debug.Write(model.Subject);
Debug.Write(model.Body);
Debug.Write(model.Email);
...
}