0

我有两个模型。

例如,模型 A包含属性的基本获取集(即)

[Required] 
[StringLength(100)]
[Display(Name = "Comment: ")]
public string Comment { get; set; }

public bool IsSuccess { get; set; }

模型二使用模态a中的属性,即

public ModelA Deposit { get; set; }
public ModelA Withdrawal { get; set; }
public ModelA Transfer { get; set; }

在我的视图中,我所做的只是在一页中使用 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 {}))
4

0 回答 0