创建我的模型 Jobs 的 DropDownList 并在 CreateEmployeesViewModel 中使用它

Create DropDownList of my model Jobs and use it in CreateEmployeesViewModel

首先,如果我的英语不是很好,请原谅。

我有点坚持这个。我想创建一个职位列表,并能够通过下拉列表选择员工所在的职位。

这就是我的工作模型。这是创建与我正在使用的数据库的连接的模型。

public partial class jobs
{
    public jobs()
    {
        this.employees= new HashSet<employees>();
    }

    public int id_job { get; set; }
    public string job{ get; set; }//NameJob

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

但是对于员工模型我创建了一个视图模型如下。

public class CreateEmployeesViewModel
{
    [Required (ErrorMessage = "It is necessary to enter a name")]
    [Display(Name = "Name")]
    public string Name{ get; set; } //Name

    [Required (ErrorMessage = "It is necessary to enter the Last Name ")]
    [Display(Name = "LastName")]
    public string LName{ get; set; } //LastName

    [Required (ErrorMessage = "What's your employee's job title?")]
    public int Job{ get; set; } //idjob
}

在我的控制器中,我有以下内容

//Get Add
public ActionResult Add()
{
    return View();
}

而对于 post

[HttpPost]
public ActionResult Add(CreateEmployeesViewModel model)
{
    if (!ModelState.IsValid)
    {
        return View(model);
    }

    using (var db = new DBExerciseEntities())
    {
        var emp = new employees();//New Employee
        emp.id_status = 1;//By default I set the new user as Active
        emp.name= model.Name;//Get Name
        emp.lname= model.LName;//get Last Name
        /*This is what I want to turn into DropDownList. Instead of typing the job "int" I want
         *to get the list of registered jobs*/
        emp.id_job = model.Job;//get id_job

        db.employees.Add(emp);
        db.SaveChanges();
    }
    return Redirect(Url.Content("~/CEmployees/"));
}

视图如下

@model Exercise.Models.ViewModels.CreateEmployeesViewModel
@{
    ViewBag.Title = "AddUser";
}
    
<h2>@ViewBag.Title</h2>

<div class="row">
    <div class="col-md-12">
        @using (Html.BeginForm("Add", "CEmployees", FormMethod.Post, new { }))
        {
            @Html.AntiForgeryToken()
            @Html.ValidationMessage("Error", new { @class = "text-danger", @type = "text" })
                        
            @Html.LabelFor(d => d.Name)
            @Html.TextBoxFor(d => d.Name, new { @class = "form-control" })
            @Html.ValidationMessage("Name", new { @class = "text-danger" })
            <br />
            @Html.LabelFor(d => d.LName)
            @Html.TextBoxFor(d => d.LName, new { @class = "form-control" })
            @Html.ValidationMessage("LName", new { @class = "text-danger" })
            <br />
            <!-- I get the name of the [display] assigned in the model-->
            @Html.LabelFor(d => d.Job)
            @Html.TextBoxFor(d => d.Job, new { @class = "form-control" })<!--How can I do DropDownList?-->
            <!-- mensajes de error  -->
            @Html.ValidationMessage("Job", new { @class = "text-danger" })
            <br />
            <div style="text-align:right;">
                <input type="submit" class="btn btn-success" value="AddUser" />
            </div>
        }
    </div>
</div>

如果你能帮助我,那将非常有帮助,因为我看到那些使用静态列表的人这样做或者只是令人困惑。

我只想提一下,我依靠不同的代码来获得我目前拥有的东西,而且我是 MVC 的新手。

很简单。这是我的解决方案。希望对你有帮助,我的朋友:))

  1. 首先,您需要在添加控制器中添加1个列表作业。

     public ActionResult Add()
     {
         List<SelectListItem> lstJobs = new List<SelectListItem>
         {
             new SelectListItem { Text = "Select", Value = "0" },
             new SelectListItem { Text = "Teacher", Value = "1" },
             new SelectListItem { Text = "Engineer", Value = "2" },
             new SelectListItem { Text = "Accountant", Value = "3" }
         };
         ViewData["job"] = lstJobs;
         return View();
     }
    
  2. 然后,在视图中显示列表作业。

         @using (Html.BeginForm("Add", "Employees", FormMethod.Post, new { }))
         {
             @Html.AntiForgeryToken()
             @Html.ValidationMessage("Error", new { @class = "text-danger", @type = "text" })
    
    
             @Html.LabelFor(d => d.Name)
             @Html.TextBoxFor(d => d.Name, new { @class = "form-control" })
             @Html.ValidationMessage("Name", new { @class = "text-danger" })
             <br />
             @Html.LabelFor(d => d.LName)
             @Html.TextBoxFor(d => d.LName, new { @class = "form-control" })
             @Html.ValidationMessage("LName", new { @class = "text-danger" })
             <br />
             <!-- I get the name of the [display] assigned in the model-->
             @Html.LabelFor(d => d.Job)
             @Html.DropDownList("Job", ViewData["job"] as List<SelectListItem>, new { @class = "form-control" })
             @*@Html.TextBoxFor(d => d.Job, new { @class = "form-control" })*@
             <!-- mensajes de error  -->
             @Html.ValidationMessage("Job", new { @class = "text-danger" })
             <br />
             <div style="text-align:right;">
                 <input type="submit" class="btn btn-success" value="AddUser" />
             </div>
         }
     </div>
    

最后,当您提交表单时,您将获得工作价值。

如无必要,请不要使用 ViewData。由于正在使用视图模型,我们只需要在该视图模型中有另一个 属性 来包含可用职位列表。


视图模型

首先,我会将模型重命名为 CreateEmployeeViewModel 而不是 CreateEmployeesViewModel,因为您一次只创建一个员工。然后我会重命名一些属性并删除一些不必要的数据注释:

public class CreateEmployeeViewModel
{
    [Required(ErrorMessage = "It is necessary to enter a name")]
    public string Name{ get; set; } //Name

    [Required(ErrorMessage = "It is necessary to enter the Last Name ")]
    [Display(Name = "LastName")]
    public string LName{ get; set; } //LastName

    [Required(ErrorMessage = "What's your employee's job title?")]
    public int SelectedJobId { get; set; } //idjob

    public IDictionary<int, string> AvailableJobs { get; set; }
}

这里我使用 IDictionary 来包含可用职位列表,因为您只有 ID 和姓名。如果您要传递的属性超过 2 个,则可以为每个可用的作业选项创建自己的视图模型 class,并改用 IEnumerableICollection


在控制器中初始化视图模型

接下来,在 HttpGet 添加操作方法上,您需要从数据库中获取可用职位列表并将其加载到视图模型,然后 return 将其加载到视图:

public ActionResult Add()
{
    var vm = new CreateEmployeeViewModel
    {
        AvailableJobs = new Dictionary<int, string>();
    };

    using (var db = new DBExerciseEntities())
    {
        vm.AvailableJobs = db.jobs
            .ToDictionary(x => x.id_job, x => x.job);
    }

    return View(vm);
}

风景

在视图中,您可以使用 @Html.DropdownListFor() 帮助程序为 SelectedJobId 生成下拉输入。

我也将你的 @Html.ValidationMessage 更改为 @Html.ValidationMessageFor()

顺便说一下,我看到你用了Bootstrap css classes。来吧!你可以制作一个更好的UI:

@model Exercise.Models.ViewModels.CreateEmployeeViewModel
@{
    ViewBag.Title = "AddUser";
}
    
<h2>@ViewBag.Title</h2>

@using (Html.BeginForm("Add", "CEmployees", new { area = "" }, FormMethod.Post, new { }))
{
    @Html.AntiForgeryToken()
    @Html.ValidationMessage("Error", new { @class = "text-danger", @type = "text" })
                
    <div class="form-group">
        @Html.LabelFor(d => d.Name)
        @Html.TextBoxFor(d => d.Name, new { @class = "form-control" })
        @Html.ValidationMessageFor(d => d.Name, new { @class = "text-danger" })
    </div>
    <div class="form-group">
        @Html.LabelFor(d => d.LName)
        @Html.TextBoxFor(d => d.LName, new { @class = "form-control" })
        @Html.ValidationMessageFor(d => d.LName, new { @class = "text-danger" })
    </div>
    <div class="form-group">
        @Html.LabelFor(d => d.SelectedJobId)
        @Html.DropdownListFor(d => d.SelectedJobId, 
            new SelectList(Model.AvailableJobs, "Key", "Value"), 
            new { @class = "form-control" }
        )
        @Html.ValidationMessageFor(d => d.SelectedJobId, new { @class = "text-danger" })
    </div>
    <div class="text-right">
        <button type="submit" class="btn btn-success">Add User</button>
    </div>
}

当表单回发到服务器时,SelectedJobId 应该包含用户的选择。