How popular Dropdownlistfor with information from a foreign key?

Asked

Viewed 613 times

0

I have these two classes and I need to popular a Dropdownlistfor with the information of the classes ModeloVeiculo, this Dropdownlistfor will be made in the create.cshtml of the class Veiculo, I believe the correct question would be, how to upload information to a Dropdownlistfor, and this information is from a foreign key!

public class Veiculo
{
    public int ID { get; set; }            
    public string Tipo { get; set; }
    public ModeloVeiculo ModeloVeiculo { get; set; }
}

public class ModeloVeiculo
{
    public int ID { get; set; }    
    public string Descricao { get; set; }
}

View:

<div class="editor-field">
    @Html.DropDownListFor(model => model.ModeloVeiculo, 
        new SelectList(Model.ModeloVeiculo, "ID", "Descricao"))
    @Html.ValidationMessageFor(model => model.ModeloVeiculo)
</div>
  • @Tiago Silva said silly I really need a Dropdownlistfor!

3 answers

1

The strange thing is that his class Veiculo, refers to only one ModeloVeiculo, and when using a CheckBox, you would be allowing the user to select more than one option. Which I find somewhat inconsistent.

But presenting a solution:

You’ll have to list all the ModeloVeiculo, go through ViewData/ViewBag and add them through a foreach:

[Controller]
ViewData["ModeloVeiculos"] = contexto.ModeloVeiculos.toList();

Then in the View:

@{
    var modeloVeiculos = ViewData["ModeloVeiculos"] as IEnumerable<ModeloVeiculo>;
}

@foreach (var modeloVeiculo in modeloVeiculos )
{
    <div>
      <label>
       @Html.CheckBox("chk", false, new { @value = modeloVeiculo.ID })
       @modeloVeiculo.Nome
      </label>
    </div>
}

So to receive and process this data on Controller.

string[] modelos = collection["chk"].Split(',');
var modeloVeiculos = new List<ModeloVeiculo>();
int parser;
foreach (string modelo in modelos)
{
      if (!modelo.Contains("false"))
      {
         if (int.TryParse(modelo, out parser))
             modeloVeiculos.Add(contexto.ModeloVeiculo.FirstOrDefault(x=>x.ID == parser));
      }
}
  • Hello @Diego Zanardo thanks for the help, but I think I expressed myself wrong did not work your code ( or I could not implement correctly), what happens and I wrote checkbox however what I need is Dropdownlistfor, in the class Modeloveiculo sera add several models and those that are add when filling the class Vehicle when arriving in the field Modeloveiculo, I need a Dropdownlistfor bring me the options of the models that were filled in the class Vehicle!! Thanks for the help once again!!

1

I don’t know if I understand this correctly, but I’ll answer as I understand it.

You can create a class to be your own Model which will contain the Vehicle properties and a list for the user to select the Vehicle Model like this:

public class VeiculoViewModel
{
    public VeiculoViewModel()
    {
        //Inicializa a lista de Modelos de Veiculo
        ModelosDeVeiculo = new List<SelectListItem>();     
    }

    public VeiculoViewModel(List<ModeloVeiculo> modelosDeVeiculo):this()
    {
        PreencherListaDeModelosDeVeiculo(modelosDeVeiculo);
    }

    //Dados do Veiculo
    public int ID { get; set; }
    public string Tipo { get; set; }

    //Lista de Modelos do Veiculo
    public int IdModeloSelecionado { get; set; }
    public List<SelectListItem> ModelosDeVeiculo { get; set; }

    //Preenche a lista de Modelos do Veiculo
    private void PreencherListaDeModelosDeVeiculo(List<ModeloVeiculo> modelosDeVeiculo)
    {
        foreach(var modelo in modelosDeVeiculo)
        {
            ModelosDeVeiculo.Add(
                new SelectListItem() { 
                    Text = modelo.Descricao, 
                    Value = modelo.ID
                    }
            );
        }
    }
}

In the Controller you can get a list of your Vehicle Models and pass it to your Model, which will finally fill the list.

public class ControllerVeiculo
{
    public ActionResult Create()
    {
        //Recupera uma lista de Modelos do Veiculo
        var listaDeModelosDeVeiculo = _repositorioModeloVeiculo.ObterTodos();
        return View(new VeiculoViewModel(listaDeModelosDeVeiculo));
    }
}

Already in his View you could render the Dropdownlistfor thus:

@Html.DropDownListFor(model => model.IdModeloSelecionado, Model.ModelosDeVeiculo)

0


A friend of mine helps me the problem was solved that way:

[Display(Name = "Modelo do veículo")]
public int? ModeloVeiculoID { get; set; }

[ForeignKey("ModeloVeiculoID")]
public virtual ModeloVeiculo ModeloVeiculo { get; set; }

Browser other questions tagged

You are not signed in. Login or sign up in order to post.