简体   繁体   中英

how do convert a string List into type IEnumerable?

I am doing a registration System for two different users; Staff and Student. and now in the fields I also have a Dropdown List. the other Fields which are Text fields are working perfectly and data can be saved to the Database, but My dropDown is giving me an error that says The ViewData item that has the key Faculty is of type System.String but must be of type IEnumerable<SelectListItem> .

Model

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; }


  }

View

@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>

Controller

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. Change to ViewBag.Faculties
  2. You should use DropDownListFor extension for clarity.

     <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> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM