Search code examples
c#asp.netasp.net-mvctextboxdropdown

Populate a textbox based on selected value from dropdown using ASP.NET MVC


I tried to search posts, without any result either, maybe I didn't use the right words.

I am using ASP.NET MVC to create a webpage with a form.

The form has a dropdownlist and a textbox.

The dropdownlist is populated with values from the database.

The textbox will populate with a value from the same table and the dropdownlist, based on the selected dropdownlist value.

My goal is to call a function from my controller inside of my view, is that possible?

My code below

Models

namespace InsGE.Models
{
    public class PersonModel
    {
        public List<SelectListItem> Fruits { get; set; } //DropDownList

        public string Names { get; set; } //Textbox
        
    }
}

Controller

namespace InGE.Controllers
{
    public class HomeController : Controller
    {
        private static List<SelectListItem> PopulateFruits()
        {
            string sql;

            List<SelectListItem> items = new List<SelectListItem>();

            string constr = ConfigurationManager.ConnectionStrings["cn"].ConnectionString;

            using (MySqlConnection con = new MySqlConnection(constr))
            {
                sql = @String.Format("SELECT * FROM `dotable`; ");

                using (MySqlCommand cmd = new MySqlCommand(sql))
                {
                    cmd.Connection = con;
                    con.Open();

                    using (MySqlDataReader sdr = cmd.ExecuteReader())
                    {
                        while (sdr.Read())
                        {
                            items.Add(new SelectListItem
                            {
                                Text = sdr["sName"].ToString(),
                                Value = sdr["sCode"].ToString()
                            });
                        }
                    }
                    con.Close();
                }
            }

            return items;
        }

        [HttpPost]
        public ActionResult Index(PersonModel person)
        {    
            string sNames = person.Names;

            PersonModel fruit = new PersonModel();
            fruit.Fruits = PopulateFruits();

            return View();
        }

        public ActionResult Index()
        {
            return View();
        }

        public ActionResult About()
        {
            ViewBag.Message = "Your application description page.";

            return View();
        }

        public ActionResult Contact()
        {
            ViewBag.Message = "Your contact page.";

            return View();
        }
    }
}

View

@Html.DropDownListFor(m => m.Fruits, Model.Fruits, "Please select")
@Html.TextBoxFor(m => m.Names)

Solution

  • You can populate the text box when selecting an item in the dropdown by using javascript.

    The following code should help you in the right direction. Place the code at the bottom of your view.

    @section scripts
    {
        <script>
    
            document.getElementById('ddlFruits').addEventListener('change', function() {
                var textBox = document.getElementById('textBoxId');
                textBox.value = this.options[this.selectedIndex].value;
            });
            
        </script>
    {
    

    We add a addEventListener to the dropdown when the page loads with a function that runs everytime the user selects a fruit in the dropdown. When the user selects a fruit the function in the 'change' event fires and updates the textbox with the selected text from the dropedown.

    Update based on comments

    Add the following controller method:

    [HttpGet]
    public ActionResult GetGps(string fruit)
    {
        PersonModel fruit = new PersonModel();
        var gps = fruit.GetGps(fruit);
        return gps;
    }
    

    You will need jQuery for this to work: https://jquery.com/download/

    Add the following jQuery code in your script tag:

    $("#ddlFruits").change(function () {
    
        var fruit = this.text();
    
        $.ajax({
            url: '/Home/GetGps',
            type: "GET",
            data: { fruit },
            success: function (gps) {
                $("#textBox").val(gps);
            },
            error: function (err) {
                console.log(err.statusText);
            }
        });
    }