私は2つのモデルを持っています。
たとえば、モデル Aには、属性の基本的な get セットが含まれています (つまり)
[Required]
[StringLength(100)]
[Display(Name = "Comment: ")]
public string Comment { get; set; }
public bool IsSuccess { get; set; }
モデル 2は、モーダル a で属性を使用します。つまり、
public ModelA Deposit { get; set; }
public ModelA Withdrawal { get; set; }
public ModelA Transfer { get; set; }
私のビューでは、非常によく似たフィールドを持つ 1 つのページで 3 つのフォームを使用するだけです。同じ理由で出金も振込も問題なく動作。コードは3つすべてでほぼ同じです
ただし、入金を行っている場合、投稿の ActionResult がモデルに渡されていません。
public ActionResult Index()
{
SetViewBagAccounts();
var model = new ModelB {};
return View(model);
}
[HttpGet]
public ActionResult Deposit()
{
return View();
}
[HttpPost]
public ActionResult Deposit(ModelB model)
{
int acct = Convert.ToInt32(Request.Form["Accounts"]);
var comment = model.Deposit.Comment;// This causes **NullReferenceException**
}
http 投稿で表示されるエラーはNullReferenceExcption
.
デバッグすると、アクション メソッドに渡されるモデルDeposit
がすべて空になります。
以下はビューのサンプルです
@model Login.Models.ModelB
@{
ViewBag.Title = "ATM";
}
<h2>ATM</h2>
<div id="leftpanel" style="position:absolute;left:0;width:33%;">
@using (Html.BeginForm("Deposit", "ATM", FormMethod.Post, new {}))
{
<div>
<fieldset>
<legend>Deposit Money</legend>
<div>@Html.LabelFor(u=>u.Deposit.AccountNumber1)</div>
<div>@Html.DropDownList("Accounts", "-- Select Account --")
</div>
<div>@Html.LabelFor(u=>u.Deposit.Amount)</div>
<div>@Html.TextBoxFor(u=>u.Deposit,new {style = "width:150px"})
@Html.ValidationMessageFor(u=>u.Deposit.Amount)
</div>
<div>@Html.LabelFor(u=>u.Deposit.Comment)</div>
<div>@Html.TextAreaFor(u=>u.Deposit.Comment,new {style = "width:250px"})
@Html.ValidationMessageFor(u=>u.Deposit.Comment)
</div>
<input type="submit" value ="Submit" style="width:31%;"/>
<input type="reset" value ="Clear" style="width:31%;"/>
</fieldset>
</div>
}
The div for deposit is pretty much copied again for withdrawal and transfer, only changed bit is :
@using (Html.BeginForm("Withdrawal", "ATM", FormMethod.Post, new {}))
@using (Html.BeginForm("Transfer", "ATM", FormMethod.Post, new {}))