I came across all other similar question on SO but I couldn't understand how to implement the solutions to my case, or which solution. This is my 2nd day in MVC and I'm stuck with something probably very simple.
What I'm trying to do is, checking a condition and returning to register page with a warning if the condition is met. When it happens, dropdownlist gives the titular error.
Checking for conditions before triggering SP. Problematic one is CompanyExists.
[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public ActionResult Register(RegisterViewModel model, FormCollection coll)
{
bool UserExists = CompanyDB.User_Check_Exists(model.Email);
bool CompanyExists = CompanyDB.Company_Check_Exists(model.CountryCode, model.TaxIdNo);
if (!ModelState.IsValid)
{
return View(model);
}
if (CompanyExists)
{
ViewBag.CompanyExists = CompanyExists;
return View(model);
}
if (coll["chkContract"] != "on")
{
ViewBag.ContractError = true;
return View(model);
}
ViewBag.UserExists = UserExists;
if (UserExists)
{
string UserEmail = model.Email;
ViewBag.UserEmail = model.Email;
}
string error = String.Empty;
RegistrationDB.Registration_Add(model, out error);
return View("RegisterComplete");
}
Dropdown population:
public class MVCUtility
{
public static ClaimsIdentity CurrentClaimsIdentity{
get { return null; }
}
public static List<SelectListItem> DataTableToListItem(DataTable Table, string ValueField, string TextField) {
List<SelectListItem> items = new List<SelectListItem>();
foreach (DataRow dr in Table.Rows) {
SelectListItem item = new SelectListItem() { Value = dr[ValueField].ToString(), Text = dr[TextField].ToString() };
items.Add(item);
}
return items;
//SelectList list = new SelectList(items);
//return list;
}
}
and the dropdown line at register.cshtml
@Html.Bootstrap().DropDownListFor(t => t.CountryCode, MVCUtility.DataTableToListItem((DataTable)ViewBag.CountryList, "Code", "Name")).HtmlAttributes(new { @style = "width:100%;" })
What I understood from other questions was, I need to repopulate the dropdown list by sending data to it before the return(View);
line. I don't know how I can manage it with these parameters.