隐藏在视图中设置但在控制器中为null

时间:2014-04-22 04:02:16

标签: asp.net asp.net-mvc code-first

我尝试在控制器中获取一个值,它在视图中设置(在隐藏字段中),但在post方法中,该字段为空。 我的模特:

 public partial class Customer
{
    public int CustomerId { get; set; }
    public string CompanyName { get; set; }


    public int? CustomerAddressId { get; set; }
    [ForeignKey("CustomerAddressId")]
    public virtual CustomerAddress CustomerAddress { get; set; }

    public int? CustomerAddressBillingId { get; set; }
    [ForeignKey("CustomerAddressBillingId")]
    public virtual CustomerAddressBilling CustomerAddressBilling { get; set; }

    public int? CustomerBankId { get; set; }
    [ForeignKey("CustomerBankId")]
    public virtual CustomerBank CustomerBank { get; set; }

    public virtual ICollection<CustomerLink> CustomerLink { get; set; }
}

我的观点:

@using (Html.BeginForm())
{
@Html.AntiForgeryToken()

<div class="form-horizontal">
    <hr />
    @Html.ValidationSummary(true)
    @Html.HiddenFor(model => model.CustomerId)
    @Html.HiddenFor(model => model.CustomerAddressId)
    @Html.HiddenFor(model => model.CustomerAddressBillingId)
    @Html.HiddenFor(model => model.CustomerBankId)

    <div class="form-group">
        @Html.LabelFor(model => model.CompanyName, new { @class = "control-label col-md-2" })
        <div class="col-md-10">
            @Html.TextBoxFor(model => model.CompanyName, new { @class = "form-control" })
            @Html.ValidationMessageFor(model => model.CompanyName)
        </div>
    </div>

    <div class="form-group">
        <div class="col-md-offset-2 col-md-10">
            @Html.ActionLink("Cancel", "Index", null, new { @class = "btn btn-default" })
            @Html.ActionLink("Address", "EditAddress", new { id = Model.CustomerId }, new { @class = "btn btn-default" })
            @Html.ActionLink("Billing Address", "EditAddressBilling", new { id = Model.CustomerId }, new { @class = "btn btn-default" })
            @Html.ActionLink("Bank Details", "EditBank", new { id = Model.CustomerId }, new { @class = "btn btn-default" })
            @Html.ActionLink("Links", "EditLink", new { id = Model.CustomerId }, new { @class = "btn btn-default" })
            <input type="submit" value="Save" class="btn btn-success" />
        </div>
    </div>
</div>
}

我的控制器方法:

 // GET: /Customer/Edit/5
    public ActionResult Edit(int id)
    {
        Customer customer = _db.GetCustomer(id);
        if (customer == null)
        {
            return HttpNotFound();
        }

        return View(customer);
    }

    [HttpPost]
    [ValidateAntiForgeryToken]
    public ActionResult Edit(Customer customer)
    {
        if (ModelState.IsValid)
        {
            _db.Edit(customer);
            _db.Save();
            return RedirectToAction("Index");
        }
        return View(customer);
    }

真正奇怪的是,CustomerId值在控制器中不为null,但我对CustomerAddressId执行完全相同的操作,并且这个值为null。 有什么建议吗?

1 个答案:

答案 0 :(得分:0)

最后我发现,我的属性在我的模型中没有正确绑定^^