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
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 :
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 :
[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 :
[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)
{
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.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
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[
^]