Mvc:获取dropdownlistFor框的选定值

时间:2015-06-08 19:19:01

标签: asp.net-mvc-4

在我的域名中,我有这项服务

    public class StudentService
        {
            private readonly IStudentRepository _studentRepository;

            public StudentService(IStudentRepository studentRepository)
            {
                _studentRepository = studentRepository;
            }

            public StudentDto DisplayStudentInformation()
            {
                var objStuSec = _studentRepository.DisplayStudentSection();
                return objStuSec;
            }  
        }

这是我的studentDto

    public class StudentDto
        {
            public string StudentId { get; set; }
            public string FirstName { get; set; }
            public string LastName { get; set; }
            public string EmailAddress { get; set; }
            public List<DepartmentDto> GetAllDepartments;
        }

这是我的家庭控制器代码

    public class HomeController : Controller
        {
            private StudentService _objStudentService;

            public HomeController(StudentService objStudentService)
            {
                _objStudentService = objStudentService;
            }

            public ActionResult Index()
            {
                ViewBag.Message = "This is a Test";

                var displayform =  _objStudentService.DisplayStudentInformation();

                return View(displayform);
            }     
        }

这是我的表单

的html
    @using System.Net.Mime
    @model Zakota.University.Domain.DTO.StudentDto

    <form action="" method="post">

        <div>
            <label>First Name</label>
            @Html.TextBoxFor(x=>x.FirstName, new { id = "testid1", name="firstname" })
        </div>
        <div>
            <label>Last Name</label>
            @Html.TextBoxFor(x=>x.LastName, new { id = "testid1", name="lastname" })

        </div>
        <div>
            <label>Email Address</label>     
            @Html.TextBoxFor(x=>x.EmailAddress, new { id = "testid1", name="emailaddress" })
        </div>
        <div>
            <label>Department</label>
            @Html.DropDownListFor( x=> x.GetAllDepartments,new SelectList(Model.GetAllDepartments,"DepartmentId","DepartmentDescription"), new {@class = "mydropdown", name="dept"})
        </div>
        <div>
            <label></label>
            <input type="submit" value="submit"/>
        </div>  

    </form>

我希望能够从dropdownListFor框中获取部门的选定值。我作为选定的值得到null。 请协助。所有其他值都是正确的。下面的代码是控制器代码的一部分。我刚决定把它分开。

      [HttpPost]
            public ActionResult Index(StudentDto objstudent)
            {

                string strFirstName = objstudent.FirstName;
                string strLastName = objstudent.LastName;
                string strEmailAddress = objstudent.EmailAddress;
                string strDept = Request.Form["dept"];

                var displayform = _objStudentService.DisplayStudentInformation();

                return View(displayform);
            }

1 个答案:

答案 0 :(得分:0)

<select>元素回发单个值。您无法将<select>绑定到复杂对象的集合(在您的情况下为List<DepartmentDto>)。首先创建一个表示您要编辑的视图模型

public class StudentVM
{
  [Display(Name = "First Name")]
  [Required(ErrorMessage = "Please enter your first name")]
  public string FirstName { get; set; }
  .... // other properties of StudentDto 
  [Display(Name = "Department")]
  [Required(ErrorMessage = "Please select a department")]
  public int SelectedDepartment { get; set; }
  public SelectList DepartmentList { get; set; }
}

接下来,您的StudentDto模型不应包含包含所有部门集合的属性。您对DropDownListFor()的使用表明每个学生只有一个部门,因此该财产应该是`public DepartmentDto&gt;部;

控制器

public ActionResult Create()
{
  StudentVM model = new StudentVM();
  ConfigureCreateViewModel(model);
  return View(model);
}

[HttpPost]
public ActionResult Create(StudentVM model)
{
  if(!ModelState.IsValid)
  {
    ConfigureCreateViewModel(model); // reassign the select list
    return View(model); // return the view so user can correct errors
  }
  StudentDto student = new StudentDto()
  {
    FirstName = model.FirstName,
    LastName = model.LastName,
    EmailAddress = mdoel.EmailAddress,
    Department = db.Departments.Find(model.SelectedDepartment) // modify to suit
  }
  // save StudentDto and redirect
}

private void ConfigureCreateViewModel(StudentVM model)
{
  List<DepartmentDto> departments = // call a service to get a collection of all departments
  model.DepartmentList = new SelectList(departments, "DepartmentId","DepartmentDescription");
}

查看

@model yourAssembly.StudentVM
@using (Html.BeginForm())
{
  @Html.LabelFor(m => m.FirstName)
  @Html.TextBoxFor(m => m.FirstName)
  @Html.ValidationMessageFor(m => m.FirstName)
  .... // other controls of StudentVM
  @Html.LabelFor(m => m.SelectedDepartment)
  @Html.DropDownListFor(m => m.SelectedDepartment, Model.DepartmentList, "--Please select--")
  @Html.ValidationMessageFor(m => m.SelectedDepartment)
  <input type="submit" value="submit"/>
}

附注:

  1. 使用@Html.LabelFor(m => m.FirstName)而不是<label>First Name</label><label>是与控件关联的元素 (单击它将焦点设置为关联的控件) - 您的使用情况 什么都不做,因为它缺少for属性
  2. html帮助器方法正确地为元素提供idname属性。在你的情况下,你生成无效的HTML 创建重复的id属性(前3个元素有 id="testid1")并且您永远不应该尝试设置name 属性(在前3个案例中,您只需将其设置为它 无论如何已经是,但在下拉的情况下,你试图 将其更改为name="dept",幸运的是,这不起作用 - 因为 如果确实如此,绑定会失败!)
  3. 您还应该考虑在视图中添加验证属性 模型属性,例如[Required(ErrorMessage="Please enter a first name")]以及包含@Html.ValidationMessageFor(m => m.FirstName)
  4. 的视图