How popular DropDownListFor with information from a foreign key?

0

I have these two classes and I need a DropDownListFor with the information of the ModeloVeiculo classes, and this DropDownListFor will be done in create.cshtml of class Veiculo , I believe the correct question would be, how to load information into a DropDownListFor, this information being of 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>
    
asked by anonymous 29.08.2014 / 03:21

3 answers

0

A friend of mine helped me, the problem was solved this way:

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

[ForeignKey("ModeloVeiculoID")]
public virtual ModeloVeiculo ModeloVeiculo { get; set; }
    
08.09.2014 / 01:55
1

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

But presenting a solution:

You will have to list all ModeloVeiculo , go through ViewData/ViewBag and add them through foreach :

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

Then in 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>
}

Then to receive and treat this data in 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));
      }
}
    
29.08.2014 / 13:54
1

I do not know if I understood correctly, but I will respond as I understand.

You can create a class to be your Model that 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 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));
    }
}

In your View you could render the DropDownListFor like this:

@Html.DropDownListFor(model => model.IdModeloSelecionado, Model.ModelosDeVeiculo)
    
01.09.2014 / 17:18