简体   繁体   中英

Binding DropdownList property to controller method in ASP.NET Core

I'm trying to get a dropdown working on the create view for a particular model object. In this case, the model in question is Department, and within that object, there is another model object referenced called Division.

My Department model is a fairly basic POCO except for the property called Division which references another POCO (which, mind you, has simply an Id field and a Name field for the most part).

I already have a working dropdown for the create view (see code below)

    <div class="form-group">
        <label asp-for="Division" class="control-label"></label>
        @Html.DropDownListFor(dept => dept.Division, new SelectList(ViewBag.Divisions, "Id", "Name"))
    </div>

Yes, in the Create method that returns the view I'm populating the ViewBag.Divisions list and that's all working as planned.

However, in the Create method of my controller, while it's binding to the other (text) fields on the view I cannot figure out how to get it to populate the Division property for the Department object with the selection from the drop-down. My create method is below:

public async Task<IActionResult> Create([Bind("Id,Name,Description,IsActive,Division")] Department department)
{
    if (ModelState.IsValid)
    {
        _context.Add(department);
        await _context.SaveChangesAsync();
        return RedirectToAction(nameof(Index));
    }
    return View(department);
}

Also, here are my model classes:

public class Division
{
    [Key]
    public int Id { get; set; }
    [Required]
    [Display(Name = "Division Name")]
    public string Name { get; set; }
    [Display(Name = "Active")]
    public bool IsActive { get; set; }
}
public class Department
{
    [Key]
    public int Id { get; set; }
    [Required]
    [Display(Name = "Department Name")]
    public string Name { get; set; }
    public string Description { get; set; }

    public Division Division { get; set; }
    [Display(Name = "Active")]
    public bool IsActive { get; set; }
}

The idea being that a particular department belongs to (and is associated with) a single division.

Thanks!

Write your Department class as follows:

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

    [ForeignKey("Division")]
    public int DivisionId {get; set;}

    [Required]
    [Display(Name = "Department Name")]
    public string Name { get; set; }

    public string Description { get; set; }

    [Display(Name = "Active")]
    public bool IsActive { get; set; }

    public Division Division { get; set; }
}

Then in the controller method:

public async Task<IActionResult> Create([Bind("Id,Name,Description,IsActive,DivisionId")] Department department)
{
    if (ModelState.IsValid)
    {
        _context.Add(department);
        await _context.SaveChangesAsync();
        return RedirectToAction(nameof(Index));
    }
    return View(department);
}

Then in the View:

<div class="form-group">
        <label asp-for="Division" class="control-label"></label>
        @Html.DropDownListFor(dept => dept.DivisionId, new SelectList(ViewBag.Divisions, "Id", "Name"))
</div>

Here is a simple demo , you could try it

Add a ViewModel with a IList as the property for your dropdownlist items.

 public class DepartmentViewModel
{
    public int Id { get; set; }
    public string Name { get; set; }
    public IList<int> Divisions { get; set; }
}

The code in Create.cshtml

@model BindDropDownList.Models.DepartmentViewModel
<div class="form-group">
     <label asp-for="@Model.Divisions" class="control-label"></label>
     @Html.DropDownListFor(depart=>depart.Divisions , (List<SelectListItem>)ViewBag.Divisions)
</div>

In Controller,retrieve ViewBag.Divisions

 ViewBag.Divisions = _context.Division.Select(d => new SelectListItem { Value=d.Id.ToString(),Text=d.Name}).ToList();

Change the Create method like below

public async Task<IActionResult> Create(DepartmentViewModel department)
    {
        //Add department
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM