Populate (Bind) TextBox based on selected value from DropDownList using jQuery in ASP.Net MVC

Last Reply one month ago By dharmendr

Posted one month ago

Hi,

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)

 

Posted one month ago

Hi comunidadmexi...,

Check this example. Now please take its reference and correct your code.

Model

public class PersonModel
{
    public List<SelectListItem> Fruits { get; set; } //DropDownList
    public int Id { get; set; }
    public string Names { get; set; } //Textbox
}

Namespaces

using System.Configuration;
using System.Data.SqlClient;

Controller

public class HomeController : Controller
{
    // GET: Home
    public ActionResult Index()
    {
        PersonModel model = new PersonModel();
        model.Fruits = PopulateFruits();
        return View(model);
    }

    [HttpPost]
    public ActionResult Index(PersonModel person)
    {
        string sNames = person.Names;
        person.Fruits = PopulateFruits();
        return View(person);
    }

    public JsonResult GetFruitName(int id)
    {
        return Json(GetFruitNameById(id), JsonRequestBehavior.AllowGet);
    }

    private static List<SelectListItem> PopulateFruits()
    {
        string sql;
        List<SelectListItem> items = new List<SelectListItem>();
        string constr = ConfigurationManager.ConnectionStrings["constr"].ConnectionString;
        using (SqlConnection con = new SqlConnection(constr))
        {
            sql = string.Format("SELECT * FROM Fruits");
            using (SqlCommand cmd = new SqlCommand(sql))
            {
                cmd.Connection = con;
                con.Open();
                using (SqlDataReader sdr = cmd.ExecuteReader())
                {
                    while (sdr.Read())
                    {
                        items.Add(new SelectListItem
                        {
                            Text = sdr["FruitName"].ToString(),
                            Value = sdr["FruitId"].ToString()
                        });
                    }
                }
                con.Close();
            }
        }

        return items;
    }

    private static string GetFruitNameById(int id)
    {
        string sql;
        List<SelectListItem> items = new List<SelectListItem>();
        string constr = ConfigurationManager.ConnectionStrings["constr"].ConnectionString;
        using (SqlConnection con = new SqlConnection(constr))
        {
            sql = string.Format("SELECT FruitName FROM Fruits WHERE FruitId = @Id");
            using (SqlCommand cmd = new SqlCommand(sql))
            {
                cmd.Connection = con;
                cmd.Parameters.AddWithValue("@Id", id);
                con.Open();
                string name = Convert.ToString(cmd.ExecuteScalar());
                con.Close();

                return name;
            }
        }
    }
}

View

@model TextBox_DropDownList_Change_MVC.Models.PersonModel

@{
    Layout = null;
}

<!DOCTYPE html>

<html>
<head>
    <meta name="viewport" content="width=device-width" />
    <title>Index</title>
    <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
    <script type="text/javascript">
        $(function () {
            $('[id*=ddlFruits]').on('change', function () {
                var fruitId = $(this).find("option:selected").val();
                if (fruitId != "") {
                    $.ajax({
                        type: "POST",
                        url: "/Home/GetFruitName",
                        data: "id=" + fruitId,
                        success: function (response) {
                            if (response != "") {
                                $('[id*=txtName]').val(response);
                            } else {
                                $('[id*=txtName]').val('');
                            }
                        }
                    });
                } else {
                    $('[id*=txtName]').val('');
                }
            });
        });
    </script>
</head>
<body>
    @Html.DropDownListFor(m => m.Id, Model.Fruits, "Please select", new { @id = "ddlFruits" })
    @Html.TextBoxFor(m => m.Names, new { @id = "txtName" })
</body>
</html>

Screenshot