In this article I will explain with an example, how to Call Controller’s Action method on DropDownList Change (SelectedIndexChanged) in ASP.Net MVC Razor.
The DropDownList will be placed inside a Form and when an Item (Option) is selected, the Form will be submitted using the JavaScript onchange (SelectedIndexChanged) event handler of the DropDownList in ASP.Net MVC Razor.
Database
This article makes use of a table named Fruits whose schema is defined as follows.
The Fruits table has the following records.
Note: You can download the database table SQL by clicking the download link below.
Namespaces
You will need to import the following namespaces.
using System.Configuration;
using System.Data.SqlClient;
using System.Collections.Generic;
Model
The following Model class has two properties FruitId and FruitName.
public class FruitModel
{
public int FruitId { get; set; }
public string FruitName { get; set; }
}
Controller
The Controller consists of two Action methods.
Action method for handling GET operation
Inside this Action method, the PopulateFruits method is called.
Inside the PopulateFruits method, the records from the Fruits table are fetched using DataReader and generic list collection of FruitModel class is populated.
Finally, the generic list collection of FruitModel class objects is returned to the View.
Action method for handling POST operation
This Action method handles the call made from the POST function from the View.
When the Form is submitted due to the DropDownList OnChange (SelectedIndexChanged) event, the posted values are captured through the Request.Form collection.
The values of FruitId and FruitName are fetched and are set into a TempData object which will be later displayed in View using JavaScript Alert Message Box.
public class HomeController : Controller
{
// GET: Home
public ActionResult Index()
{
List<FruitModel> fruits = PopulateFruits();
return View(fruits);
}
[HttpPost]
public ActionResult Submit(FormCollection formcollection)
{
TempData["Message"] = "Fruit Name: " + formcollection["FruitName"];
TempData["Message"] += "\\nFruit Id: " + formcollection["FruitId"];;
return RedirectToAction("Index");
}
private static List<FruitModel> PopulateFruits()
{
List<FruitModel> fruits = new List<FruitModel>();
string constr = ConfigurationManager.ConnectionStrings["Constring"].ConnectionString;
using (SqlConnection con = new SqlConnection(constr))
{
string query = " SELECT FruitName, FruitId FROM Fruits";
using (SqlCommand cmd = new SqlCommand(query))
{
cmd.Connection = con;
con.Open();
using (SqlDataReader sdr = cmd.ExecuteReader())
{
while (sdr.Read())
{
fruits.Add(new FruitModel
{
FruitName = sdr["FruitName"].ToString(),
FruitId = Convert.ToInt32(sdr["FruitId"])
});
}
}
con.Close();
}
}
return fruits;
}
}
View
Inside the View, in the very first line the FruitModel class is declared as IEnumerable which specifies that it will be available as a Collection.
The View consists of an HTML Form which has been created using the Html.BeginForm method with the following parameters.
ActionName – Name of the Action. In this case the name is Submit.
ControllerName – Name of the Controller. In this case the name is Home.
FormMethod – It specifies the Form Method i.e. GET or POST. In this case it will be set to POST.
The Form consists of a DropDownList and a Hidden Field.
The DropDownList is generated using the Html.DropDownList Html Helper method.
The first parameter is the Name attribute of the DropDownList.
The second parameter is the Model class property for populating the DropDownList i.e. its source of data.
The third parameter is the text of the Default Item of the DropDownList. If not specified there will be no default item in the DropDownList.
Finally, the fourth and the last parameter allows to specify the HTML attributes such as id, class etc.
The DropDownList has been assigned a jQuery onchange event handler, when an item is selected in the DropDownList, the Text of the selected item is copied in the Hidden Field and the Form will be submitted.
When the Form gets submitted, the FruitId and FruitName values are sent to the Controller.
Finally, the FruitId and FruitName values of the selected Fruit are displayed using JavaScript Alert Message Box.
@model IEnumerable<Call_Controller_DropDownList_Change_MVC.Models.FruitModel>
@{
Layout = null;
}
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width"/>
<title>Index</title>
<style type="text/css">
body
{
font-family: Arial;
font-size: 10pt;
}
</style>
</head>
<body>
@using (Html.BeginForm("Submit", "Home", FormMethod.Post, new { @name = "Form1" }))
{
@Html.DropDownList("FruitId", new SelectList(Model, "FruitId", "FruitName"), "Please select", new { @id = "ddlFruits" })
@Html.Hidden("FruitName", null, new { @id = "hfFruitName" })
}
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script type="text/javascript">
$("body").on("change", "#ddlFruits", function () {
$("#hfFruitName").val($(this).find("option:selected").text());
document.forms["Form1"].submit();
});
</script>
@if (TempData["Message"] != null)
{
<script type="text/javascript">
$(function () {
alert("@TempData["Message"]");
});
</script>
}
</body>
</html>
Screenshot
Downloads