Fill selectoption with titles stored in a database

3

I have a <select> and I want it to show titles that are stored in a database. I have found several forms but none has been useful. If someone can guide me, I would appreciate it: D

This is what I have in my application of c #

<div class="col-sm-4">
  <div class="form-group form-group-default input-group required">
    <label>Titulo de Lanzamiento</label>
    <select class="form-control" id="tipoApp" name="tipoApp" data-init-plugin="select2" required>
       <option value=" "></option>
    </select>
  </div>
</div>

And this is my table

create table Portal
(
  Id_Dashboard int,
  Fecha_Activacion date,
  Fecha_Vencimiento date, 
  Pais varchar(200),
  Titulo_Lanzamiento varchar(200),
  Nombre_Banner varchar(200),
  Url_Img varchar(200),
  Estatus int
)

The titles that I seek to obtain are according to the country

    
asked by Pikoh 25.05.2017 в 16:56
source

2 answers

1

Well you have to create the connection to your database and assign the datasource of your list the result of your query:

string ConnectString = "server=**tu servidor**;database=**nombre de tu base de datos**;integrated security=SSPI"; //reemplazala por tu cadena de conexion
string QueryString = "select * from Portal";

SqlConnection myConnection = new SqlConnection(ConnectString);   
command = new SqlCommand("SELECT_LANZAMIENTO", myConnection);
command.CommandType = System.Data.CommandType.StoredProcedure;

connection.Open();

DataTable dt = new DataTable();
dt.Load(command.ExecuteReader());

tipoApp.DataSource = dt;
tipoApp.DataTextField = "Pais";
tipoApp.DataValueField = "Id_Dashboard";
tipoApp.DataBind();
    
answered by 25.05.2017 в 17:21
0

Assuming you have that single table and that you pass country as a parameter. The first thing you have to do is save in a collection all the Portal whose country is equal to the one collected as parm. your driver:

public ActionResult Prueba(string pais )
{           
    var collection = db.Portals.Where(s => s.Pais == pais).ToList();
    ViewBag.Titulos = new SelectList(collection, "Titulo_Lanzamiento", "Titulo_Lanzamiento")
    return View();
}

and in form use the helper html to render the ViewBag as what you want

 @Html.DropDownList("Titulos", null, String.Empty, new { @class = "form-control")

Note: for this example I use Entity Framework and LINQ but the idea is that, I hope it helps you

    
answered by 25.05.2017 в 19:44