The records from the database will be populated into a
Generic List collection of
Model class objects and then will be saved into a
ViewBag object.
Inside the View, the
ViewBag object will be passed to the
Html.DropDownList Helper function for populating the
DropDownList in
ASP.Net MVC Razor.
Database
I have made use of the following table Fruits with the schema as follows.
I have already inserted few records in the table.
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 Model class consists of following properties.
public class FruitModel
{
public int FruitId { get; set; }
public string FruitName { get; set; }
}
Controller
The Controller consists of following 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 stored into a
ViewBag object.
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, 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()
{
ViewBag.Fruits = PopulateFruits();
return View();
}
[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
HTML Markup
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
DropDownList is generated using the
Html.DropDownList Helper method.
The first parameter is the
Name attribute of the
DropDownList.
The second parameter is the
ViewBag object 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.
When the
Submit Button is clicked, the Form gets submitted and 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.
@{
Layout = null;
}
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>Index</title>
</head>
<body>
@using (Html.BeginForm("Submit", "Home", FormMethod.Post))
{
@Html.DropDownList("FruitId", new SelectList(ViewBag.Fruits, "FruitId", "FruitName"), "Please select", new { @id = "ddlFruits" })
@Html.Hidden("FruitName", null, new { @id = "hfFruitName" })
<input type="submit" value="Submit" />
}
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/3.7.1/jquery.min.js"></script>
<script type="text/javascript">
$("body").on("change", "#ddlFruits", function () {
$("#hfFruitName").val($(this).find("option:selected").text());
});
</script>
@if (TempData["Message"] != null)
{
<script type="text/javascript">
$(function () {
alert("@TempData["Message"]");
});
</script>
}
</body>
</html>
Screenshot
Downloads