I need to fill Html.DropdownListFor()
in my view through razor, so far I have the following, two classes where I get the data that I need to recover from my db plus the controller by GET
to recover the data and send it to the seen by ViewBag
So far I have the following code
CLASSES
public class Region
{
public int Id { get; set; }
public string NombreRegion { get; set; }
public List<Region> Regiones { get; set; }
}
public class Data
{
private Region _Region;
public Data()
{
_Region = new Region();
}
public List<Region> GetRegion()
{
try
{
using (SqlConnection conn = new SqlConnection(DetamaticAPI.DataBase.Connection.ConnString))
{
string SQL = string.Empty;
SQL += "SELECT id, Region";
SQL += " FROM Region";
try
{
conn.Open();
SqlCommand command = new SqlCommand(SQL, conn);
SqlDataAdapter sqlDataAdapter = new SqlDataAdapter(command);
DataSet dataset = new DataSet();
sqlDataAdapter.Fill(dataset, "Region");
conn.Close();
for (int i = 0; i < dataset.Tables[0].Rows.Count; i++)
{
_ Region.Regiones.Add(new Region()
{
Id= Convert.ToInt32(dataset.Tables[0].Rows[i]["id"].ToString()),
NombreRegion= dataset.Tables[0].Rows[i]["Region"].ToString()
});
}
return _Region.Regiones;
}
catch (Exception e)
{
throw;
}
}
}
catch (Exception e)
{
throw;
}
}
}
CONTROLLER BY GET
public ActionResult Index()
{
ViewBag.Region = _Data.GetRegion();
return View();
}
VISTA
@Html.DropDownListFor(m => m.Region, new SelectList(ViewBag.Region, "Value", "Text"))
But all the above gives me the following exception
System.Web.HttpException: 'DataBinding:' DetamaticTotem.Controllers.Region 'does not contain a property with the name' Value '.'
Well as it says there is because it does not contain the spropiedades value
and text
... how should this list be created to contain those properties? I had seen the SelectList
and SelectListItem
but I do not know how to use them or modify my code to implement it ..