Click here to Skip to main content
15,885,546 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
I have a form whereby i need to do select multiple employees on a HtmlDropDownFor. I have used an SelectListItem and in my controller i am getting an exception 'Cannot implicitly convert type 'string' to string[] ' on the property pertaining to the employee i.e on line


C#
request.EmployeeNumber = Convert.ToString(formcollection["EmployeeNumber"]);


I also have a related exception 'Cannot implicitly convert type 'string[]' to 'string'' on the function that loads an individual employee in the model i.e

This is how im getting the employees :
C#
private static IEnumerable<SelectListItem> GetEmployees()
       {
           string department = string.Empty;
           department = System.Web.HttpContext.Current.Session["Department"].ToString();

           string number = string.Empty;
           number = System.Web.HttpContext.Current.Session["UserId"].ToString();

           List<SelectListItem> employees = new List<SelectListItem>();
           using (SqlConnection conn = new SqlConnection(Helpers.DatabaseConnect))
           {

               SqlCommand cmd = new SqlCommand("SELECT DisplayName,EmployeeNumber FROM Users WHERE Active=" + Convert.ToInt32(Helpers.parameters.active) + " AND Department=" + Convert.ToInt32(department) + "", conn);

               conn.Open();
               SqlDataReader dr = cmd.ExecuteReader();
               while (dr.Read())
               {
                   employees.Add(new SelectListItem
                   {
                       Text = dr["DisplayName"].ToString(),
                       Value = dr["EmployeeNumber"].ToString()
                   });
               }
               conn.Close();
           }

           return employees;
       }


In model OverTimeRequest.cs i have :
C#
[Required]
        [Display(Name = "Employee ")]
        public string[] EmployeeNumber { get; set; }
        public Employee Employee { get; set; }
        public String DisplayName { get; set; }
		public IEnumerable<SelectListItem> employees { get; set; }




Controller :
C#
[HttpPost]
       public ActionResult NewOverTimeRequest(FormCollection formcollection)
       {

           Models.Employee.OverTimeRequest request = new Models.Employee.OverTimeRequest();
           try
           {

               var batch = new OvertimeBatch();
               batch.AppliedBy = Convert.ToString(Session["UserId"]);
               batch.Justification = Convert.ToString(formcollection["Justification"]);
               batch.rate = Convert.ToInt32(formcollection["RateId"]);
               batch.NumberOfHour = Convert.ToInt32(formcollection["Hours"]);
               batch.Month = Convert.ToDateTime(formcollection["PayMonth"]);
               batch.AppliedOn = DateTime.Now;
               batch.id = batch.save();

               request.employees = GetEmployees();
               request.Rates = PopulateOverTimeRates();

               request.EmployeeNumber = Convert.ToString(formcollection["EmployeeNumber"]);
               request.RateId = Convert.ToInt32(formcollection["RateId"]);
               request.Justification = Convert.ToString(formcollection["Justification"]);
               request.Hours = Convert.ToInt32(formcollection["Hours"]);
               request.PayMonth = Convert.ToDateTime(formcollection["PayMonth"]);
               request.AppliedBy = Convert.ToString(Session["UserId"]);
               request.AppliedOn = DateTime.Now;

               DateTime Today = request.PayMonth;
               var startdate = new DateTime(Today.Year, Today.Month, 1);
               request.PayMonth = startdate.AddMonths(1).AddDays(-1);

               PayRunController payrun = new PayRunController();

               var employees = request.EmployeeNumber.Split(',');


               request.OverTimeAmount = 0.00;

               double total = 0.0;
               if (ModelState.IsValid)
               {
                   foreach (var employee in employees)
                   {
                      // request.OverTimeAmount = payrun.CalculateOverTimeAmount(employee, request.RateId);
                       total += request.OverTimeAmount;

                       using (SqlConnection conn = new SqlConnection(Helpers.DatabaseConnect))
                       {

                           SqlCommand cmd = new SqlCommand("SubmitOverTimeRequest", conn);
                           cmd.CommandType = CommandType.StoredProcedure;


                           cmd.Parameters.AddWithValue("@EmployeeNumber", employee);
                           cmd.Parameters.AddWithValue("@OverTimeRate", request.RateId);
                           cmd.Parameters.AddWithValue("@Justification", request.Justification);
                           cmd.Parameters.AddWithValue("@NumberOfHours", request.Hours);
                           cmd.Parameters.AddWithValue("@PayMonth", request.PayMonth);
                           cmd.Parameters.AddWithValue("@Amount", request.OverTimeAmount);
                           cmd.Parameters.AddWithValue("@AppliedBy", request.AppliedBy);
                           cmd.Parameters.AddWithValue("@AppliedOn", request.AppliedOn);
                           cmd.Parameters.AddWithValue("@OverTimeBatch", batch.id);

                           conn.Open();
                           cmd.ExecuteNonQuery();

                       }

                   }
                   batch.TotalAmount = total;
                   batch.updateTotalAmount();

                   return RedirectToAction("OverTime");
               }

           }

           catch (Exception ex)
           {
               ViewBag.ErrorMessage = ex.Message;
               return View(request);
           }

           return RedirectToAction("OverTime");
       }


This is how im getting the data in the view NewOverTimeRequest.cshtml :


HTML
@Html.DropDownListFor(m => m.EmployeeNumber, Model.employees, "Please Select", htmlAttributes: new { @class = "form-control" })
                                                               @Html.ValidationMessageFor(model => model.EmployeeName, "", new { @class = "text-danger" })


Anyone with ideas on how i can properly implement the functionality.

What I have tried:

I have searched sources and suggestions point to that i should use a range in GetEmployees function. Also i have tried using a forech in the view as below but its not working since the example im using does not use a select element, but rather HtmlDropDownFor/Html.ListBoxFor


C#
m.EmployeeNumber, Model.employees, "Please Select", htmlAttributes: new { @class = "form-control" })
                                                               @Html.ValidationMessageFor(model => model.EmployeeName, "", new { @class = "text-danger" })>


I am following the answer from this thread asp.net mvc 3 - How do you properly create a MultiSelect <select> using the DropdownList helper? - Stack Overflow[^]
Posted
Updated 1-Nov-22 20:20pm
Comments
[no name] 24-Dec-19 8:58am    
You decalred public string[] EmployeeNumber { get; set; } so EmployeeNumber is an array...

The reason that you are getting this error is that EmployeeNumber is declared as an array of strings (string[]) and you are attempting to populate it from a single string directly.

I believe that you want this just to be a string, and not an array of them.OverTimeRequest.cs
C#
[Required]
[Display(Name = "Employee ")]
public string[] EmployeeNumber { get; set; }
//           ^^ you probably want a string, not a string[] which would be an array

public Employee Employee { get; set; }
public String DisplayName { get; set; }
public IEnumerable<SelectListItem> employees { get; set; }

If you should actually want this to be an array, then you would populate it like this
C#
EmployeeNumber = new string[] { Convert.ToString(formcollection["EmployeeNumber"]) };
 
Share this answer
 
Comments
Tshumore 25-Dec-19 8:16am    
@MadMyche. I want EmployeeNumber to be an array , its an overtime requisition for multiple employees hence I have used ListBoxFor. in the controller i have var employees = request.EmployeeNumber.Split(','); which then extracts the selected employees.

I have amended the code to have :
request.EmployeeNumber = new string[] { Convert.ToString(formcollection["EmployeeNumber"]) };

but im getting an exception Argument 1: Cannot convert from 'System.Collections.Generic.IEnumerable<string> to string for the employee object on the line
foreach (var employee in employees)
{
request.OverTimeAmount = payrun.CalculateOverTimeAmount(employee, request.RateId); //employee

What am i doing wrong.
Member 11201441 1-Apr-21 6:56am    
Sir My question is how pass string [] to var as a parameter
EmployeeNumber = new string[] { Convert.ToString(formcollection["EmployeeNumber"]) };
this solution only work in single index ,
can you please tell this statment with loop
 
Share this answer
 
Comments
Richard Deeming 2-Nov-22 5:03am    
Your question is not a solution to someone else's question.

If you want to ask for more information about a solution, click the "Have a Question or Comment?" button under that solution and post a comment. Do not post your comment as another solution.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900