I've a Project model like below:

public class Project
{
    public int Id { get; set; }

    ....

    [Required]
    public virtual ApplicationUser Client { get; set; }

    [Key]
    [ForeignKey("Client")]
    public string ClientID;


    [Required]
    public virtual ApplicationUser ProjectManager { get; set; }

    [Key]
    [ForeignKey("ProjectManager")]
    public string ProjectManagerID;

    ....


}

In tried to pass users with specified role inside create action like below,using ViewBag:

// GET: /Project/Create
public ActionResult Create()
{
    populateRoles();
    SelectList PMs = new SelectList(projectManagers, "Id", "Name");
    ViewBag.ProjectManagerID = PMs;
    SelectList Clients = new SelectList(clients, "Id", "Name");
    ViewBag.ClientID = Clients;
    return View();
}

And here is the part of Razor View for drop-downs:

<div class="form-group">
    @Html.Label("Project Manager", new { @class = "col-md-2 control-label" })
    <div class="col-md-10">
        @Html.DropDownList("ProjectManagerID", ViewBag.ProjectManagerID as SelectList, new { @class = "col-md-10 control-label" })
    </div>
</div>
<div class="form-group">
    @Html.Label("Client", new { @class = "col-md-2 control-label" })
    <div class="col-md-10">
        @Html.DropDownList("ClientID", ViewBag.ClientID as SelectList, new { @class = "col-md-10 control-label" })
    </div>
</div>

There is no problem up to here, but on form post my model will not have valid state:

[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create([Bind(Include = "Id,Name,Progress,CreateDate")] Project project)
{
    /*---------------------populate select lists ------*/
    populateRoles();
    SelectList PMs = new SelectList(projectManagers, "Id", "Name");
    ViewBag.ProjectManagerID = PMs;
    SelectList Clients = new SelectList(clients, "Id", "Name");
    ViewBag.ClientID = Clients;
    /*-----------try to fix invalid modelstate ---------*/
    string projectManagerID = Request["PMs"];
    string clientID = Request["Clients"];
    project.ProjectManagerID = projectManagerID;
    project.ClientID = clientID;

    if (ModelState.IsValid) // <-Invalid modelstate because required foreign key properties
    {
        dbContext.Projects.Add(project);
        dbContext.SaveChanges();
        return RedirectToAction("Index");
    }

    return View(project);
}

The Question: How to pass required foreign key properties here?

Related posts

Recent Viewed