Hi, I have to fill out a dropdownlist with the information that this query gives me.
Select Unit from Unit Measures where Status = 'Active'
This query should bring me the units that have the active state but I do not know how to implement it since I'm just starting in asp I do not know if it is done from the controller or from the model and then how to call it in the view
I already read a part but I get the error that it can not be null I do not know if the query in visual studio does not show results because in sql if it shows the data this is the controller
public class MaterialesController : Controller
{
private BDMonlic1Entities db = new BDMonlic1Entities();
int r;
// GET: Materiales
public ActionResult Index()
{
ViewBag.Fruits = PopulateFruits();
//var materiales = db.Materiales.Include(m => m.UnidadMedidas);
return View();
//return View(materiales.ToList());
}
private static List<Materiales> PopulateFruits()
{
List<Materiales> fruits = new List<Materiales>();
string constr = ConfigurationManager.ConnectionStrings["Constring"].ConnectionString;
using (SqlConnection con = new SqlConnection(constr))
{
string query = "select u.Unidad, u,idunidad from materiales m join UnidadMedidas u on u.IdUnidad=m.IdUnidad where u.Estado = 'Activo'";
using (SqlCommand cmd = new SqlCommand(query))
{
cmd.Connection = con;
con.Open();
using (SqlDataReader sdr = cmd.ExecuteReader())
{
while (sdr.Read())
{
fruits.Add(new Materiales
{
Estado = sdr["Unidad"].ToString(),
IdUnidad = Convert.ToInt32(sdr["idunidad"])});
}
}
con.Close();
}
}
return fruits;
}
and this is the view where I should call the query data
<div class="form-group">
@Html.LabelFor(model => model.IdUnidad, "Unidad *", htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.DropDownList("IdUnidad", new SelectList(ViewBag.Fruits, "idunidad", "Unidad"),"Please select", new { @unidad = "Estado" })
@Html.ValidationMessageFor(model => model.IdUnidad, "", new { @class = "text-danger" })
</div>
</div>
thanks