How to get values to popular a dropdown dynamically

Asked

Viewed 276 times

0

I am developing in . NET MVC and in my application, I have a form that registers people via Ajax. This registered element should appear in a list dropdown, it should appear dynamically without updating the page, someone knows some way to do it?

I can’t get the names on my list dropdown without updating! There would be some way when click on dropdown it shows the entries entered in the previous field?

1 answer

1

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

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));
   }
}

Of 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 of Partial View created for the dropdown:

@model SelectList
@DateTime.Now
@Html.DropDownList("drop", Model)

Browser other questions tagged

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