MVC4 - 未将模型传递给控制器​​以进行操作

时间:2013-10-01 14:02:37

标签: c# asp.net-mvc-4 entity-framework-4 controller

我有两个型号。

模型A 例如包含atrributes的基本get set(即)

[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 {}))

0 个答案:

没有答案