Fill a DropDownList depending on a conditional query in asp.net mvc 5 entity framework

1

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

    
asked by Yhonatan Montenegro 27.12.2018 в 19:35
source

1 answer

0

I do it in the following way, I do not know if it is useful for you but here I am sending it to you, these are examples:

COUNTRIES

IEnumerable<Pais> paises()
    {
        List<Pais> temporal = new List<Pais>();

        SqlCommand cmd = new SqlCommand("Select Idpais, NombrePais from tb_paises", con);

        con.Open();

        SqlDataReader rea = cmd.ExecuteReader();

        while (rea.Read())
        {
            Pais p = new Pais();
            p.Idpais = rea.GetString(0);
            p.NombrePais = rea.GetString(1);

            temporal.Add(p);
        }

        rea.Close();

        con.Close();

        return temporal;
    }

ADD [GET]

public ActionResult Agregar() //Esta es la presentación de la pagina
    {
        //Envío a la pagina la lista de los paises
        ViewBag.paises = new SelectList(paises(), "idpais", "nombrepais");

        //Enviar a la pagina un nuevo Cliente
        return View(new Cliente());
    }

ADD [POST]

[HttpPost]
public ActionResult Agregar(Cliente c)
        {
        ......................

        ViewBag.paises = new SelectList(paises(), "idpais", "nombrepais", c.idpais); //El 4to parametro sirve que se quede seleccionado el ultimo valor que escogí del DropDown al momento de realizar otro "Create"

        return View(c);
    }

VIEW OF ADDING

@using (Html.BeginForm()) 
{
<div class="form-group">
            @Html.LabelFor(model => model.idpais, htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.DropDownList("idpais", (SelectList)ViewBag.paises)
            </div>
        </div>
}

You're probably a bit confused but I'll explain, what I do is create a separate method and then call it and fill in the data. The ActionResult "Add" what it does is an insert, but that does not interest us, what matters is the code that is below, in the GET method you see that I am putting a viewBag countries, this viewBag I am sending it to the view with the value "new SelectList (countries ()," idpais "," nombrepais ");", which is a list where the first parameter would be the method that we created, then the second would be the values that are to be sent and the third the values that are going to be shown. When you run it all will be fine, but when you want to send values to the database in the case of a register, we use the POST, in the ActionView Add [POST] what we do is put the same and with a fourth parameter that would be the value that was selected in the GET, remember that in the GET only the view is shown and in the POST the data is sent to the database, it would be 2 different views, that's why we put the same thing. And finally we put the view "@ Html.DropDownList (" idpais ", (SelectList) ViewBag.paises)", this code would be the dropdown and the first parameter would be the id of the selectList that was in the GET and POST, the second parameter would be the ViewBag that we are seeing, also remember that the ViewBag are used to pass data from the controller to the view. And that would be it, if you have questions DO NOT HESITATE TO CONSULT ME. :)

    
answered by 28.12.2018 в 19:16