本文介绍了其他型号的下拉列表mvc5的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

第一次使用MVC开发应用程序,并遇到了一个问题,该问题导致在带有教师列表的学生create视图中出现一个下拉列表.

First time using MVC to develop an app and have run into an issues populating a dropdown in the student create view with a list of teachers.

我有2个模型

public class Student
{

    [Required]
    [Display(Name = "ID")]
    public int ID { get; set; }
    [Required]
    [StringLength(100)]
    [DataType(DataType.Text)]
    [Display(Name = "First Name")]
    public string FirstName { get; set; }
    [Required]
    [StringLength(100)]
    [DataType(DataType.Text)]
    [Display(Name = "Last Name")]
    public string LastName { get; set; }
    [Required]
    [DataType(DataType.Date)]
    [Display(Name = "Date of Birth")]
    public DateTime? DateOfBirth { get; set; }
    [Required]
    [DataType(DataType.EmailAddress)]
    [Display(Name = "Email Address")]
    public string EmailAddress { get; set; }
    [Required]
    [DataType(DataType.PhoneNumber)]
    [Display(Name = "Contact Number")]
    public string ContactNumber { get; set; }
    [Required]
    [StringLength(100)]
    [DataType(DataType.Text)]
    [Display(Name = "Parent/Guardian Name")]
    public string ParentGuardianName { get; set; }

    public Teacher Teacher { get; set; }


    public MembershipOption MembershipOption { get; set; }

    public ICollection<Progress> Progress { get; set; }
    public ICollection<Report> Report { get; set; }
    [DataType(DataType.Date)]
    [Display(Name = "Signed Up Date")]
    public DateTime? SignedUpDate { get; set; }
    [Display(Name = "Active")]
    public bool Active { get; set; }



}

 public class Teacher
{
    [Required]
    [Display(Name = "ID")]
    public int ID { get; set; }
    [Required]
    [StringLength(100)]
    [DataType(DataType.Text)]
    [Display(Name = "First Name")]
    public string FirstName { get; set; }
    [StringLength(100)]
    [DataType(DataType.Text)]
    [Display(Name = "Last Name")]
    public string LastName { get; set; }
    [Display(Name = "Active")]
    public bool Active { get; set; }
    [Required]
    [EmailAddress]
    [Display(Name = "Email")]
    public string Email { get; set; }

}

}

我具有如下所示的学生模型的创建视图

I have the create view of the student model that looks like this

    <div class="form-group">
    @Html.LabelFor(model => model.ParentGuardianName, htmlAttributes: new { @class = "control-label col-md-2" })
    <div class="col-md-10">
        @Html.DropDownListFor(m => m.Teacher, // 1. Store selected value in Model.State;
                                         // when page is rendered after postback,
                                         // take selected value from Model.State.

                                       // 2. Take list of values from Model.States
                                       Model.Teacher,

                                       // 3. Text for the first 'default' option
                                       "- Please select a Teacher -",

                                       //4. A class name to assign to <select> tag
                                       new { @class = "form-control" })
        @Html.ValidationMessageFor(model => model.Teacher, "", new { @class = "text-danger" })
    </div>
</div>

教师"的下拉列表由于教师"为空而引发异常.

The dropdownlist for Teachers throws an exception due to Teacher being null.

如何将教师下拉列表添加到该学生中以创建cshtml?

How do i go about adding the teachers drop down list to this student create cshtml?

我假设在调用学生模型时我需要找老师,但不确定在学生控制器中的什么位置?

Im assuming i need to get the teachers when the student model is called, but not sure where it needs to be put in the studentscontroller?

推荐答案

第二个参数应该是SelectListItem的列表,以便帮助程序方法可以使用该列表来生成SELECT选项.但是您正在尝试传递Teacher导航属性,而不是传递该属性!

The second parameter should be a list of SelectListItem's so that the helper method can use that list to generate the SELECT options. But you are trying to pass the Teacher navigational property instead of that!

您应该为您的视图创建一个视图模型,该模型具有可以接受表单输入值的属性.由于要向视图添加下拉菜单,因此请向视图模型添加2个属性.一个用于选定的值,另一个用于我们需要用来呈现下拉菜单的项目列表

You should create a view model for your view, which has properties to accept the form input values. Since you want to add a dropdown to the view, add 2 properties to the view model. one for the selected value and one for the list of items we need to use to render the dropdown

public class CreateStudent
{
    [Required]
    [StringLength(100)]
    [Display(Name = "First Name")]
    public string FirstName { get; set; }

    [Required]
    [StringLength(100)]
    [Display(Name = "Last Name")]
    public string LastName { get; set; }

    // to do : Add other properties AS NEEDED BY THE VIEW
    // Do not just copy all the properties from Entity class

    public List<SelectListItem> Teachers { set; get; }

    [Required]
    [DisplayName("Select Teacher")]
    public int SelectedTeacherId { set; get; }
}

现在,在GET操作中,您需要创建此视图模型的对象,填充Teachers集合属性并将该对象发送到视图

Now in your GET action, you need to create an object of this view model, populate the Teachers collection property and send the object to the view

public ActionResult Create()
{
    var vm = new CreateStudent();
    vm.Teachers = GetTeachers();
    return View(vm);
}

private List<SelectListItem> GetTeachers()
{
    return db.Teachers.Select(a => new SelectListItem
    {
        Value = a.Id.ToString(),
        Text = a.Name
    }).ToList();
}

现在在您的视图中(该视图是我们视图模型的强类型),我们可以使用DropDownListFor helper方法来呈现SELECT元素

Now in your view, which is strongly typed to our view model, we can use DropDownListFor helper method to render the SELECT element

@model CreateStudent
@using(Html.BeginForm())
{
    @Html.LabelFor(a=>a.FirstName)
    @Html.TextBoxFor(a=>a.FirstName)

    @Html.LabelFor(a=>a.LastName)
    @Html.TextBoxFor(a=>a.LastName)

    @Html.LabelFor(a=>a.SelectedTeacherId)
    @Html.DropDownListFor(a=>a.SelectedTeacherId , Model.Teachers, "select one")

    <input type="submit" />
}

现在在HttpPost操作中,使用与操作方法参数相同的视图模型,并从其属性中读取值,然后使用该模型创建实体类的新对象并保存它

Now in your HttpPost action, use the same view model as your action method parameter, and read the values from it's properties and use that to create a new object of your entity class and save it

[HttpPost]
public ActionResult Create(CreateStudent model)
{
  if(ModelState.IsValid)
  {
     var s = new Student { FirstName=model.FirstName };
     s.LastName = model.LastName;
     // to do : Map other property values as well from view model
     db.Students.Add(s);
     db.SaveChanges();
     return RedirectToAction("Index");
  }
  //Make sure to RELOAD the Teachers list for dropdown
  model.Teachers = GetTeachers();
  return View(model);
}

这篇关于其他型号的下拉列表mvc5的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-21 07:20