Why do I see the aforementioned error with this bit of code? The error specifically occurs in the t.TerritoryID == territoryID
section:
[HttpPost]
public ActionResult Add(EmployeeViewModel employee, string[] territories)
{
ModelState.Remove("territories");
if (ModelState.IsValid)
{
if (territories != null)
{
employee.Territories = territories.Select(territoryID => repository.Territories.FirstOrDefault(t => t.TerritoryID == territoryID));
}
employee.EmployeeID = repository.CreateEmployee(employee);
}
return RedirectToAction("Index");
}
In case you're wondering, TerritoryID
is an integer. Any suggestions on how I can rectify this issue? Thanks in advance.
Int and string are two different types, you can't directly compare them. You can convert an int to a string or vice versa.
Change territories
to an int array: var territoriesInt = territories.Select(x => int.Parse(x)).ToArray()
, and then use that.
The above code is string to int conversion. This can fail if a string doesn't contain a number. I prefer to let it fail on purpose if someone sends bad data. It can be done the opposite way, too, if you compare your territories strings to territoryID.ToString()
.
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments