@ Html.DropDownListFor Default item in the first list values

1

Good afternoon, gentlemen.

I use DropDownListFor to load lists, example load all my clients to be selected. However, I need that if a record does not appear in the listing have the option to add a new item.

I can write the code, however the problem is that the item to add a new record is at the end of my list, I would like it to be the second item. The first item is to select, second new and the others that are registered.

@Html.DropDownListFor(model => model.ClienteId, new SelectList(@ViewBag.Clientes, "Id", "Nome") ,"Selecione")

JS:

 $('#ClienteId').append($('<option>', { text: "Novo", value: 0, selected: false }));
    
asked by anonymous 17.12.2015 / 21:30

2 answers

0

It would look something like this:

$('#ClienteId').append($('<option>', { text: "Novo", value: 0, selected: false }));
var options = $('#ClienteId option');
$(options[options.size() - 1]).insertAfter($(options)[1]));
    
17.12.2015 / 21:42
0

First of all, I do not think that this ideal way to specify that a new record will be inserted, DropDownList should have only the items that can be used to fill the field in model and the optional field that is displayed when no item is selected.

You could for example have a checkbox which when checked would enable the DropDownList and when unchecked would display some other option to add a new client.

But finally, you can insert this "New" field into DropDownList from the server side as follows:

(For those who will judge me, I know it's an ugly solution, but there's nothing else that can be done to answer the OP's server-side question).

public ActionResult Index()
{
    // Vamos supor que os dados dos clientes vieram do banco de dados
    var clientes = new List<Cliente>
    {
        new Cliente { Id = 1, Nome = "Foo" },
        new Cliente { Id = 2, Nome = "Bar" }
    };

    // Com a coleção de Clientes em mãos, insira um novo Cliente no primeiro índice e atribua "Novo" à propriedade que será exibida na DropDownList
    clientes.Insert(0, new Cliente { Nome = "Novo" });

    // E agora transforme a coleção de Clientes em uma SelectList
    ViewBag.Clientes = new SelectList(clientes, "Id", "Nome");

    return View();
}
    
18.12.2015 / 00:14