来自对象的数据未传输到 ModelState

问题描述

我正在尝试向数据库添加一个具有“地址”属性的“生产者”对象。将地址添加到创建的对象后,我从 ModelState 收到错误,因为它收到的是 NULL,而不是来自创建的对象的地址。

为什么 ModelState 在“地址”上为 NULL,我该如何解决

类:

public class Producer
{
    [Key]
    public int Id { get; set; }

    [required(ErrorMessage = "The name is required.")]
    [MaxLength(30)]
    public string Name { get; set; }

    public int Funds { get; set; }

    [required(ErrorMessage = "The address is required.")]
    public int AddressId { get; set; }

    [required]
    public virtual Address Address { get; set; }

    public string UserId { get; set; }

    public virtual ApplicationUser User { get; set; }
}

来自控制器的方法

public ActionResult Create([Bind(Include = "Id,Name,Funds,AddressId,address")] Producer producer)
{
    Address address = db.Addresses.Find(producer.AddressId);
    producer.Address = address;
    address.IsFree = false;
    address.ProducerId = producer.Id;
    producer.Funds = 0;
    producer.UserId = User.Identity.GetUserId();

    if (ModelState.IsValid)
    {
        db.Entry(address).State = EntityState.Modified;
        db.Producers.Add(producer);
        db.SaveChanges();
        return RedirectToAction("ShowMyProducers");
    }  
    return View(producer);
}

查看:

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

    <div class="form-horizontal">
        <h4>Producer</h4>
        <hr />
        @Html.ValidationSummary(true,"",new { @class = "text-danger" })

        <div class="form-group">
            <label>Nume</label>
            <div class="col-md-10">
                @Html.EditorFor(model => model.Name,new { htmlAttributes = new { @class = "form-control" } })
                @Html.ValidationMessageFor(model => model.Name,new { @class = "text-danger" })
            </div>
        </div>

        <div class="form-group">
            <label>Adresa (creeată anterior)</label>
            <div class="col-md-10">
                **@Html.DropDownListFor(model => model.AddressId,new SelectList(ViewBag.Addresses,"Value","Text"),"selectează adresa",new { @class = "form-control" })**
                @Html.ValidationMessageFor(model => model.AddressId,new { @class = "text-danger" })
            </div>
        </div>

        <div class="form-group">
            <div class="col-md-offset-2 col-md-10">
                <input type="submit" value="Create" class="btn btn-default" />
            </div>
        </div>
    </div>
}

watch before checking if ModelState is valid

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)