私は、ViewModelを使用して非常に単純なフォーム送信であると感じるものを作成しようとしています。私はこれに一日中取り組んできましたが、何らかの理由で、アプリがHttpPostアクションに到達したときにEmailViewModelが空になる理由を理解できません。「NullReference例外が発生しました」「オブジェクト参照がオブジェクトのインスタンスに設定されていません」というエラーが発生します。
私のコードを見て、私がどこに夢中になっているのか教えてもらえますか?
これが私のhttpPostアクションです:
[HttpPost]
public ActionResult SendStudentAnEmail(EmailViewModel email)
{
Debug.Write(email.Subject); // First NullReferenceException
Debug.Write(email.Body);
Debug.Write(email.Email);
etc. . .
私のViewModel:
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アクションを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にキャストする必要があるのはなぜですか?単にEmailViewModelをアクションにプッシュしようとすると、NullReference例外が発生しないのはなぜですか?