Create a Dropdown List by getting the values from a table in MVC .NET Web application

Rumman Ansari   2019-03-13   Student   MS dot NET > Develop-dropdown-list-from-database-table   10244 Share

SQL Tables and Procedure

In this particular blog we will see how you can use a dropdown list inside your web application in a MVC environment

Our strategy will be:

We will have the two different table 1. aa_ManufacturerMaster_1637935 and another 2. aa_AssetMaster_1637935. While Inserting into the second table we will get the Mname field in the second table but the data with respect to the Mname , MID(as this is a foreign key reference in the second table) values will insert into the aa_AssetMaster_1637935 table.

Table Name: aa_ManufacturerMaster_1637935

This is our first table from where we will get the data for the dropdown.


CREATE TABLE aa_ManufacturerMaster_1637935
(
MID int identity(100,1) primary key,
Mname varchar(50)
)



File Name: aa_AssetMaster_1637935

This is our second table


CREATE TABLE aa_AssetMaster_1637935(
AssetID int identity(100,1) primary key,
AssetUniqueName varchar(50),
AssetType varchar(50),
ManufacturerID int foreign key references aa_ManufacturerMaster_1637935(MID),
AllocationStatus int
) 


Procedure Name: xx_sp_insert_AssetMaster

This is the procedure by which we will insert data inside the second table aa_AssetMaster_1637935


ALTER PROCEDURE xx_sp_insert_AssetMaster 
@AssetUniqueName varchar(50),
@AssetType varchar(50),
@ManufacturerID int,
@AllocationStatus int,
@AssetID int OUT
AS
BEGIN

INSERT INTO aa_AssetMaster_1637935 VALUES
(@AssetUniqueName,@AssetType,@ManufacturerID,@AllocationStatus) 
SET @AssetID = @@IDENTITY
END


.NET CODE

File Name: HomeController.cs

This method will return List . Items will be fetched from the aa_ManufacturerMaster_1637935 table.



 DB012TMS214_1819Entities dbObject = new DB012TMS214_1819Entities();

        protected List<SelectListItem> populateddlist_Manufacture()
        {
            List<aa_ManufacturerMaster_1637935> lstmfact = new List<aa_ManufacturerMaster_1637935>();
            lstmfact = dbObject.aa_ManufacturerMaster_1637935.ToList();
            List<SelectListItem> manufacturenames = new List<SelectListItem>();
            foreach (var e in lstmfact)
            {
                SelectListItem s = new SelectListItem();
                s.Text = e.Mname;
                s.Value = e.MID.ToString();
                manufacturenames.Add(s);

            }

            return manufacturenames;
        }


File Name: HomeController.cs

This is a ActionResult contoller which fetch the data from the aa_ManufacturerMaster_1637935 table which loading the page for that this is a [HttpGet]


 [HttpGet]
        public ActionResult AddAsset() {

            List<SelectListItem> ddlistvalues = new List<SelectListItem>();
            ddlistvalues = populateddlist_Manufacture();

            aa_AssetMaster_1637935 manufectureobj = new aa_AssetMaster_1637935();
            manufectureobj.namufactureName = ddlistvalues; 

            return View(manufectureobj);
             
        }



File Name: HomeController.cs

This is a ActionResult contoller which controls the action of AddAsset. This is [HttpPost] method.



 [HttpPost]
        public ActionResult AddAsset(aa_AssetMaster_1637935 assetObj)
        {
            if (ModelState.IsValid)
            {
                ObjectParameter AssetID = new ObjectParameter("AssetID", typeof(int));
                assetObj.AllocationStatus = 0;
                int rows = dbObject.xx_sp_insert_AssetMaster(assetObj.AssetUniqueName, assetObj.AssetType, assetObj.ManufacturerID, assetObj.AllocationStatus, AssetID);
                if (rows > 0)
                {
                    TempData["Message"] = "Inserted with id =" + AssetID.Value.ToString();
                    return RedirectToAction("AddAllocation");

                }

                List<SelectListItem> ddlistvalues = new List<SelectListItem>();
                ddlistvalues = populateddlist_Manufacture();
                aa_AssetMaster_1637935 manufectureobj = new aa_AssetMaster_1637935();
                manufectureobj.namufactureName = ddlistvalues;
                return View(manufectureobj);
            }
            else
            {
                return View();
            }

        } 

File Name: AddAsset.cshtml

This is view page where we are are getting the Mname (Manufacture name) through the MID (Manufacture id) in a drop down list.


@model MVCAssetManagementSystem.Models.aa_AssetMaster_1637935

@{
    ViewBag.Title = "AddAsset";
}

<h2>AddAsset</h2>

@{

    List<SelectListItem> list1 = new List<SelectListItem>();
    list1.Add(new SelectListItem
    {
        Text = "Laptop",
        Value = "Laptop",
    });
    list1.Add(new SelectListItem
    {
        Text = "Desktop",
        Value = "Desktop",
    });



    //List<SelectListItem> list2 = new List<SelectListItem>();
    //list2.Add(new SelectListItem
    //{
    //    Text = "Un Allocated",
    //    Value = "0",
    //});
    //list2.Add(new SelectListItem
    //{
    //    Text = "Allocated",
    //    Value = "1",
    //});

}


@using (Html.BeginForm())
{
    @Html.AntiForgeryToken()

    <div class="form-horizontal">

        <div>
            @Html.ActionLink("AddAsset", "AddAsset")
            <br>
            @Html.ActionLink("AddAllocation", "AddAllocation")
        </div>


        <h4>aa_AssetMaster_1637935</h4>
        <hr />
        @Html.ValidationSummary(true, "", new { @class = "text-danger" })
        <div class="form-group">
            @Html.LabelFor(model => model.AssetUniqueName, htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.EditorFor(model => model.AssetUniqueName, new { htmlAttributes = new { @class = "form-control" } })
                @Html.ValidationMessageFor(model => model.AssetUniqueName, "", new { @class = "text-danger" })
            </div>
        </div>

        <div class="form-group">
            @Html.LabelFor(model => model.AssetType, htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @*@Html.EditorFor(model => model.AssetType, new { htmlAttributes = new { @class = "form-control" } })*@
                Laptop @Html.RadioButtonFor(model => model.AssetType, "Lapto")
                Desktop @Html.RadioButtonFor(model => model.AssetType, "Desktop")
                @Html.ValidationMessageFor(model => model.AssetType, "", new { @class = "text-danger" })
            </div>
        </div>

        <div class="form-group">
            @Html.LabelFor(model => model.ManufacturerID, "ManufacturerID", htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @*@Html.DropDownList("ManufacturerID", null, htmlAttributes: new { @class = "form-control" })*@
                @Html.DropDownListFor(model => model.ManufacturerID, Model.namufactureName, "--Select Manufacture Name--")
                @Html.ValidationMessageFor(model => model.ManufacturerID, "", new { @class = "text-danger" })
            </div>
        </div>

        @*<div class="form-group">
            @Html.LabelFor(model => model.AllocationStatus, htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                // @Html.EditorFor(model => model.AllocationStatus, new { htmlAttributes = new { @class = "form-control" } })
                @Html.DropDownListFor(model => model.AllocationStatus, list2)
                @Html.ValidationMessageFor(model => model.AllocationStatus, "", new { @class = "text-danger" })
            </div>
        </div>*@

        <div class="form-group">
            <div class="col-md-offset-2 col-md-10">
                <input type="submit" value="Create" class="btn btn-default" />
            </div>
        </div>
    </div>
    
}

    <div style="background-color:orange">
        @TempData["Message"]
    </div>

<div>
    @Html.ActionLink("Index page", "Index") <br>
    @Html.ActionLink("View Asset Allocation Details", "ViewAssetAllocationDetails") 
</div>

<script src="~/Scripts/jquery-1.10.2.min.js"></script>
<script src="~/Scripts/jquery.validate.min.js"></script>
<script src="~/Scripts/jquery.validate.unobtrusive.min.js"></script>
<script src="~/Scripts/MyScripts.js"></script>



File Name:





File Name:

Aa the namufactureName properties not present in the second table it will throw an error in the view page. so this issues can be fixed though an AssetMetaClass.cs which you have to create that class inside the Model folder.


using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace MVCAssetManagementSystem.Models
{
    public class AssetMetaClass
    {
 

    }

    [MetadataType(typeof(AssetMetaClass))]
    public partial class aa_AssetMaster_1637935
    {
        public List<SelectListItem> namufactureName { get; set; }
       
    }
 
     
}