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

本文关键字:类型 IEnumerable 转换 List 字符串 | 更新日期: 2023-09-27 18:25:21

我正在为两个不同的用户进行注册系统;员工和学生。现在在字段中,我还有一个下拉列表。其他作为文本字段的字段工作正常,数据可以保存到数据库中,但我的下拉菜单显示一个错误,即具有关键字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);
    }

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

  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>