如何将字符串List转换为IEnumerable类型?

时间:2015-12-02 06:54:10

标签: c# model-view-controller drop-down-menu

我正在为两个不同的用户做一个注册系统;员工和学生。现在在这些领域我也有一个下拉列表。其他字段是文本字段工作正常,数据可以保存到数据库,但我的dropDown给我一个错误,说明具有键Faculty的ViewData项目类型为System.String但是必须是IEnumerable<SelectListItem>类型。

模型

public class RegisterClient
{

    public int UserID { get; set; }

    [Required(ErrorMessage ="Please Enter Department Name")]
    [Display(Name="Department")]
    [RegularExpression(@"^[a-zA-Z]+[ a-zA-Z-_]*$", ErrorMessage = "Use    Characters only")]
    [StringLength(100)]
    public string Department { get; set; }


    public string Faculty { get; set; }


    [Required(ErrorMessage ="Please enter Name")]
    [RegularExpression(@"^[a-zA-Z]+[ a-zA-Z-_]*$", ErrorMessage = "Use     Characters only")]
    [StringLength(50)]
    public string Name { get; set; }

    [Required(ErrorMessage ="Please enter Contact number")]
    [Display(Name="Contact Number")]
    [RegularExpression(@"^\(?([0-9]{3})\)?[-. ]?([0-9]{3})[-. ]?([0-9]  {4})$", ErrorMessage = "Entered phone format is not valid.")]
    [StringLength(10, ErrorMessage ="Contact Number must be 10 numbers")]
    public string Contact_Nr { get; set; }

    [Required(ErrorMessage ="Please Enter Surname")]
    [RegularExpression(@"^[a-zA-Z]+[ a-zA-Z-_]*$", ErrorMessage = "Use   Characters only")]
    [StringLength(50)]
    public string Surname { get; set; }

    [Required(ErrorMessage = "Please Enter Staff Number")]
    [StringLength(5, MinimumLength = 5, ErrorMessage ="Staff Number must be   5 digits only")]
    [Display(Name="Staff Number")]
    [RegularExpression("([1-9][0-9]*)", ErrorMessage = "Staff Number must be   numbers only")]
    public string Access_Num{ get; set; }

    [Required(ErrorMessage ="Please enter Email Address")]
    [EmailAddress]
    [Display(Name="Email")]
    [RegularExpression(".+\\@.+\\..+", ErrorMessage = "Please Enter your   valid email which contains the @ Sign")]
    [StringLength(128)]
    public string EmailID { get; set; }


  }

查看

@model EbikesRegistrationSystem.Models.RegisterClient

  @{
  ViewBag.Title = "Register";
  }

  <h2>Register</h2>
  <body style="background:#FFD24A">

  @using (Html.BeginForm())
  {
    @Html.AntiForgeryToken()

    <div class="form-horizontal">
        <h4>Staff Registration</h4>
        <hr />
        @Html.ValidationSummary(true, "", new { @class = "text-danger" })


        @{
            ViewBag.Title = "uYilo";
        }

        <h2></h2>
        @if (ViewData["Message"] != null)
        {
            <script language="javascript">
    alert('@ViewData["Message"]');
            </script>
        }

          <div class="form-group">
            @Html.LabelFor(model => model.Name, htmlAttributes: new { @class   = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.EditorFor(model => model.Name, new { htmlAttributes =   new { @class = "form-control" } })
                @Html.ValidationMessageFor(model => model.Name, "", new {     @class = "text-danger" })
            </div>
        </div>

       <div class="form-group">
            @Html.LabelFor(model => model.Surname, htmlAttributes: new {   @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.EditorFor(model => model.Surname, new { htmlAttributes     = new { @class = "form-control" } })
                @Html.ValidationMessageFor(model => model.Surname, "", new {     @class = "text-danger" })
            </div>
        </div>


        <div class="form-group">
            @Html.LabelFor(model => model.Contact_Nr, htmlAttributes: new {     @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.EditorFor(model => model.Contact_Nr, new {     htmlAttributes = new { @class = "form-control" } })
                @Html.ValidationMessageFor(model => model.Contact_Nr, "",     new { @class = "text-danger" })
            </div>
        </div>



        <div class="form-group">
            @Html.LabelFor(model => model.EmailID, htmlAttributes: new {     @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.EditorFor(model => model.EmailID, new { htmlAttributes      = new { @class = "form-control" } })
                @Html.ValidationMessageFor(model => model.EmailID, "", new {   @class = "text-danger" })
            </div>
        </div>

        <div class="form-group">
            @Html.LabelFor(model => model.Access_Num, htmlAttributes: new {     @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.EditorFor(model => model.Access_Num, new {   htmlAttributes = new { @class = "form-control" } })
                @Html.ValidationMessageFor(model => model.Access_Num, "",     new { @class = "text-danger" })
            </div>
        </div>



        <div class="form-group" >
                @Html.LabelFor(model => model.Department, htmlAttributes:   new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.EditorFor(model => model.Department, new {   htmlAttributes = new { @class = "form-control" } })
                @Html.ValidationMessageFor(model => model.Department, "",     new { @class = "text-danger" })
            </div>
        </div>


        <div class="form-group">
            @Html.LabelFor(model => model.Faculty, htmlAttributes: new {    @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.DropDownList("Faculty", ViewBag.Faculties as     IEnumerable<SelectListItem>,
                   "Select Faculty")
                @Html.ValidationMessageFor(model => model.Faculty, "", new {    @class = "text-danger" })
            </div>
        </div>







        <div class="form-group">
            <div class="col-md-offset-2 col-md-10">
                <input type="submit" value="Register" class="btn btn-  default" onclick="clearField()" />
            </div>
        </div>
    </div>
}

<div>
    @*@Html.ActionLink("Back to List", "Index")*@
</div>
<script>
    var clearField = function () {

        $(".form-control")
    }
</script>
@section Scripts {
    @Scripts.Render("~/bundles/jqueryval")
}
</body>

控制器

public class UserController : Controller
{
    private DataClasses1DataContext db = new DataClasses1DataContext();
    // GET: User
    public ActionResult Register()
    {

        DataClasses1DataContext db = new DataClasses1DataContext();
        ViewBag.Faculties = new SelectList(db.Faculties, "Id", "Name");
        return View();
    }



    [HttpPost]
    [ValidateAntiForgeryToken]
    public ActionResult Register(RegisterClient U)
    {
        if (ModelState.IsValid)
        {
            try
            {
                using (DataClasses1DataContext db = new   DataClasses1DataContext())
                {

                    {


                        User newone = new User();

                        newone.EmailID = U.EmailID;
                        newone.Name = U.Name;
                        newone.Surname = U.Surname;
                        newone.Contact_Nr = U.Contact_Nr;
                        newone.Department = U.Department;
                        newone.Access_Num = U.Access_Num;


                        var count = db.Users.Count(a => a.EmailID ==    U.EmailID);
                        if (count == 0)
                        {
                            db.Users.InsertOnSubmit(newone);
                            db.SubmitChanges();
                            ViewData["Message"] = "Successful Registration";
                            ModelState.Clear();

                        }
                        else
                        {
                            // something to do if user exist...
                            ViewData["Message"] = "User Exists, Register   with a new Email Address";
                            ModelState.Clear();
                        }


                    }

                }
            }
            catch (Exception ex)
            {
                string error = ex.Message;
            }

        }

        return View(U);
    }

1 个答案:

答案 0 :(得分:1)

  1. 更改为ViewBag.Faculties
  2. 为清晰起见,您应该使用DropDownListFor扩展名。

    <div class="form-group">
    @Html.LabelFor(model => model.Faculty, htmlAttributes: new {    @class = "control-label col-md-2" })
    <div class="col-md-10">
        @Html.DropDownListFor(model => model.Faculty, ViewBag.Faculties, "Select Faculty")
        @Html.ValidationMessageFor(model => model.Faculty, "", new {    @class = "text-danger" })
    </div>