如何将外键从视图传递给控制器

时间:2016-11-05 08:13:04

标签: asp.net-mvc-5

我正在研究mvc项目。 我有一个viewmodel如下

public class AddInfoViewModel
{
    public myproject.Models.DomainModels.information information { get; set; }
    public IEnumerable<myproject.Models.DomainModels.Companies> Companies { get; set; }
    public long CompanyID { get; set; }
}

观点:

<div class="form-group">
    @Html.Label("company", new { @class = "control-label col-md-2" })
    <div class="col-md-10">
        @Html.DropDownList("CompanyID", new SelectList(Model.Companies, "CompanyID", "Name"), "select company", htmlAttributes: new  {@class = "form-control" })
        @Html.ValidationMessageFor(model => model.CompanyID, "", new { @class = "text-danger" })
    </div>
</div>

这是我在控制器中的行动:

[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create(information information)
{
    informationRepository blinformation = new informationRepository();
    if (ModelState.IsValid)
    {
        double id = blinformation.GetLastIdentity() + 1;
        information.ID = Convert.ToInt32(id);
        //codes for add to db
        ...
    }
}

当我运行项目时,发送到控制器中创建操作的CompanyID为零(0)。我该如何解决这个问题?

1 个答案:

答案 0 :(得分:1)

您的代码是信任的,但您必须替换

@Html.DropDownList("CompanyID", new SelectList(Model.Companies, "CompanyID", "Name") 

with:

@Html.DropDownListFor(model => model.CompanyID,...)