Dropdown - ASP.NET MVC

Asked

Viewed 98 times

2

I’m a beginner in ASP.NET MVC and I need to create a Dropdown in a vehicle registration form where I can choose only one driver related to the vehicle that is previously registered in the database (created via Entity Framework). My code is currently like this:

Conductor

public class Condutor
{
    public int CondutorId { get; set; }

    [Required]
    public int Matricula { get; set; }

    [Required]
    public string PrimeiroNome { get; set; }

    [Required]
    public string UltimoNome { get; set; }

    [Required]
    public string CPF { get; set; }
}

Vehicle

public class Veiculo
{
    public int Id { get; set; }

    [Required]
    public string Modelo { get; set; }

    [Required]
    public string Marca { get; set; }

    [Required]
    public string Tipo { get; set; }
}

Controller

[AutorizacaoFilter] // filtro de autorizacao, localizado na pasta "Filters"
public class VeiculoController : Controller
{
    // atributos do controller para acesso ao banco de dados
    private VeiculoDAO dao;

    // construtor da classe
    public VeiculoController(VeiculoDAO dao)
    {
        this.dao = dao;
    }

    public IActionResult Index()
    {
        IList<Veiculo> lista = dao.Lista();
        return View(lista);
    }


    [HttpPost]
    public IActionResult IncluirVeiculo(Veiculo veiculo)
    {
        dao.IncluirVeiculo(veiculo);
        return RedirectToAction("Index");   
    }


    public IActionResult Cadastro()
    {
        var model = new Veiculo();
        return View(model);

    }


    // remove um veículo, através do seu id cadastrado na tabela do banco de dados
    public IActionResult RemoverVeiculo(int id)
    {
        dao.RemoverVeiculo(id);
        return RedirectToAction("Index");
    }


    // localiza um veículo pelo seu Id e o exibe na View "Ver Cadastro", para ser editado
    public IActionResult VerCadastro(int id)
    {
        Veiculo veiculo = dao.BuscaVeiculoPorId(id);
        return View(veiculo);
    }


    // edita o registro do veículo e reflete as alterações no BD
    [HttpPost]
    public IActionResult EditarVeiculo(Veiculo veiculo)
    {
        dao.AtualizaCadastro(veiculo);
        return RedirectToAction("Index");
    }

    public IActionResult BuscaVeiculo(string termo)
    {
        IList<Veiculo> veiculos = dao.BuscaPeloTermo(termo);
        return View("Index", veiculos);
    }

}

View

Ignore Enum, it was just for testing, while I couldn’t solve Dropdown

@model Veiculo

<div class="container">
	<br />
	<h2>Cadastrar veículo</h2>
	<br />

	<form class="form-horizontal" action="/Veiculo/IncluirVeiculo" method="post">
		<div class="form-group">
			<label class="control-label col-sm-2" for="text">Modelo:</label>
			<div class="col-sm-10">
				<input type="text" class="form-control" id="modelo" style="max-width:50%" placeholder="Ex: Palio, Gol, Corsa, etc" name="modelo" />
			</div>
		</div>
		<div class="form-group">
			<label class="control-label col-sm-2" for="text">Marca:</label>
			<div class="col-sm-10">
				<input type="text" class="form-control" id="marca" style="max-width:50%" placeholder="Ex: Chevrolet, Honda, Nissan, etc" name="marca" />
			</div>
		</div>
		<div class="form-group">
			<label class="control-label col-sm-2" for="text">Tipo:</label>
			<div class="col-sm-10" style="max-width:43%">
				@Html.DropDownListFor(v => v.Tipo,
		 new SelectList(Enum.GetValues(typeof(Tipo))),
		 "-- Escolha uma opção --",
		 new { @class = "form-control"})
			</div>
		</div>
		<div class="form-group">
			<div class="col-sm-offset-2 col-sm-10">
				<button type="submit" class="btn btn-success">Salvar</button>
				<button type="reset" class="btn btn-info">Limpar dados</button>
			</div>
		</div>
	</form>
</div>

Solving this example, the idea is to use other dropdowns as well, among different models. The current difficulty of mine was that, as the View is strongly typed in Vehicle, I could not create this "link" with the Driver class.

In this case, how could I create this type of Dropdown, via Entity Framework using LINQ and LAMBDA?

  • Vehicle and driver relate?

  • There is no relationship between them

  • You need to record CondutorId on the table Veiculo?

2 answers

0


You can use Viewbag to pass a listing from Controller to the View. And to make the relationship between Veiculo and Condutor would have to create a property Condutor in class Veiculo.

Would look like this:

In class VeiculoController in action Cadastro (if this is really the action of your sign-up view), you load Viewbag with the list of Drivers.

public IActionResult Cadastro()
{
    var model = new Veiculo();

    var condutores = dbContext.Condutor.Select(c => new SelectListItem()
        {
            Value = c.CondutorId.ToString(),
            Text = c.PrimeiroNome
        });

    ViewBag.Condutores = condutores;

    return View(model);
}

For you to retrieve the Condutor selected and save it on Veiculo, needs to have relationship of Condutor in the Veiculo.

public class Veiculo {

public int Id { get; set; }

[Required]
public string Modelo { get; set; }

[Required]
public string Marca { get; set; }

[Required]
public string Tipo { get; set; }

public Condutor CondutorVeiculo { get; set; }

}

And finally in view would look like this:

 @Html.DropDownListFor(model => model.CondutorVeiculo.CondutorId, (IEnumerable<SelectListItem>)ViewBag.Condutores, new { @id = "ddlCondutores", @class = "form-control" })

See if this works for you.

  • After the above implementations, Dropdownlistfor worked correctly, listing drivers and updating automatically if a new one is registered. But, it caused some problems in the CRUD of vehicles in general. When choosing the desired Dropdown option, an SQL Exception occurs: 'Sqlexception: Cannot Insert Explicit value for Identity column in table 'Conductor' when IDENTITY_INSERT is set to OFF." What could it be? (I will insert the structure of the tables in a reply).

  • I think it has to do with some mapping of the Vehicle table in the Entity. Was the Vehicle table created through Migrations in the Vehicle class? It seems that when you try to enter a record in the Vehicle table, Entity is trying to enter a record in the Driver table. And if you search for the Driver (by the Id selected in the dropdownlist) and assign this in the Vehicle object you are trying to include?

  • In this case here https://stackoverflow.com/questions/12509608/ef-code-first-cannot-insert-explicit-value-for-identity-column-in-table-when had to do with the Entity configuration.

0

Dropdown worked correctly, with new options added to the list as drivers are registered. However, several problems in the Vehicle CRUD. One of them is the Exception 'Sqlexception: Cannot Insert Explicit value for Identity column in table 'Conductor' when IDENTITY_INSERT is set to OFF." when registering a new vehicle. Below, follow the tables (created via Migrations in the Entity Framework):

Table Vehicles

CREATE TABLE [dbo].[Veiculos] (
[Id]                        INT NOT NULL,
[Modelo]                    NVARCHAR (MAX) NOT NULL,
[Tipo]                      NVARCHAR (MAX) NOT NULL,
[Marca]                     NVARCHAR (MAX) NOT NULL,
[CondutorVeiculoCondutorId] INT            NULL,
CONSTRAINT [PK_Veiculos] PRIMARY KEY CLUSTERED ([Id] ASC),
CONSTRAINT [FK_Veiculos_Condutor_CondutorVeiculoCondutorId] FOREIGN KEY ([CondutorVeiculoCondutorId]) REFERENCES [dbo].[Condutor] ([CondutorId])

);

Table Conductor

CREATE TABLE [dbo].[Condutor] (
[CondutorId]                INT            IDENTITY (1, 1) NOT NULL,
[Matricula]                 INT            NOT NULL,
[PrimeiroNome]              NVARCHAR (MAX) NOT NULL,
[UltimoNome]                NVARCHAR (MAX) NOT NULL,
[CPF]                       NVARCHAR (MAX) NOT NULL,
[CondutorVeiculoCondutorId] INT            NULL,
CONSTRAINT [PK_Condutor] PRIMARY KEY CLUSTERED ([CondutorId] ASC),
CONSTRAINT [FK_Condutor_Condutor_CondutorVeiculoCondutorId] FOREIGN KEY ([CondutorVeiculoCondutorId]) REFERENCES [dbo].[Condutor] ([CondutorId])

);

  • Try placing the attribute [Notmapped] in the Conductive property.

  • I did some tests, apparently it must be some problem of Migrations. Table Vehicle was created via Migration as well. Even putting [Notmapped], it appears another error Cannot Insert the value NULL into column 'Id', table 'Fleetcar.dbo.Vehicles'; column does not allow nulls. INSERT fails. The statement has been terminated.. I’ll check the recreation of the entity models to see if it solves the problem.

Browser other questions tagged

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