How to get values to populate a dropdown dynamically

0

I'm developing in .NET MVC and in my application, I have a form that registers people via Ajax. This element should appear in a dropdown list, it should appear dynamically without refreshing the page, does anyone know of any way to do this?

I can not get the names in my dropdown list without updating! Would there be any way to click on dropdown to show items inserted in the previous field?

    
asked by anonymous 10.03.2015 / 17:18

1 answer

1

Depending on the complexity of your screen I suggest using Javascript for this, but then I gave an example with a different alternative, to give you some ideas, I hope it helps:

Add the file to your header :

<script src="~/Scripts/jquery.unobtrusive-ajax.js"></script>

Control code:

public static class DropDownDB
{
   public static List<string> Nomes = new List<string> { "Nome 1", "Nome 2", "Nome 3" };
}

public class DropDownController : Controller
{
   public ActionResult Index()
   {
      return View();
   }

   [HttpPost]
   public ActionResult Index(string nome)
   {
      DropDownDB.Nomes.Add(nome);
      return MeuDrop();
   }

   public ActionResult MeuDrop()
   {
      return PartialView("MeuDrop", new SelectList(DropDownDB.Nomes));
   }
}

From View :

@model string

@using (Ajax.BeginForm(null, new AjaxOptions { HttpMethod = "Post", InsertionMode = InsertionMode.Replace, UpdateTargetId = "replaceDiv", OnSuccess = "$('.text').val('');" }))
{
   <input type="text" name="nome" />
   <button type="submit">Adicionar</button>
}
<div id="replaceDiv">
   @Html.Action("MeuDrop")
</div>

And Partial View created for dropdown :

@model SelectList
@DateTime.Now
@Html.DropDownList("drop", Model)
    
10.03.2015 / 17:57