Add Dropdownlist value to the database

Asked

Viewed 83 times

1

I wanted to put a dropdownlist in my view where his List value went to the database, but I only know how to add values to DropDownlist with data from a table, wanted to make a DropDownlist with three values without having to create a new table and place in my View Razor.

Here’s an example of how I do in my views:

    @model BlogWeb.ViewsModels.VisitaModel

@Html.ValidationMessage("DtIntegracao.Invalido")

@Html.ValidationMessageFor(v => v.Nome)
@Html.LabelFor(v => v.Nome, "Nome:")
@Html.TextBoxFor(a => a.Nome)

@Html.ValidationMessageFor(v => v.Rg)
@Html.LabelFor(v => v.Rg, "Rg:")
@Html.TextBoxFor(a => a.Rg)

@Html.ValidationMessageFor(v => v.DtIntegracao)
@Html.LabelFor(v => v.DtIntegracao, "Data Integração:")
@Html.TextBoxFor(v => v.DtIntegracao, "{0:dd-MM-yyyy}", new { Type = "date" })

@Html.ValidationMessageFor(v => v.ResponsavelId)
@Html.LabelFor(v => v.ResponsavelId, "Responsavel Entrada:")
@Html.DropDownListFor(v => v.ResponsavelId, new SelectList(ViewBag.Usuarios, "Id", "Nome"))

1 answer

0

Two options to be made is manual or with the enum, below follows example of the two forms

Handbook:

Create a select

<select id="Info" name="Info">
    <option value="0">Selecione</option>
    <option value="1">Info 1</option>
    <option value="2">Info 1</option>
    <option value="3">Info 1</option>
</select>

In your model create a property with the same name select

public class VisitaModel
{
    public int Info { get; set; }
}

Ready, when performing a post the Info property will have the selected value.

Enum:

Create a enum, the attribute Display is used to define which text will be displayed

public enum MeuEnum
{
    [Display(Name = "Info 1")]
    Info1 = 1,

    [Display(Name = "Info 2")]
    Info2 = 2,

    [Display(Name = "Info 3")]
    Info3 = 4
}

In your model create a property with the type of enum

public class VisitaModel
{
    public MeuEnum MeuEnum { get; set; }
}

In your view, use the helper EnumDropDownListFor

@Html.EnumDropDownListFor(model => model.MeuEnum, "Selecione", new { @class = "form-control" })

Ready, when performing a post the Meuenum property will have the selected value.

Browser other questions tagged

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