Using DropDownlist in MVC4



In MVC ddl Is Collection Of Selectlistitem Objects
In create

Method 1:

In View:
  @Html.DropDownList("BranchID", String.Empty)

In controller:
ViewBag.BranchID = new SelectList(db.M_Branches, "ID", "BranchName");


Method 2: to get the “select” option in ddl

In View:
  @Html.DropDownListFor(model => model.BranchID,    (IEnumerable<SelectListItem>)ViewBag.BRANCHVAL, "Select") 

In controller:
   ViewBag.BRANCHVAL = new SelectList(db.M_Branches, "ID", "BranchName");


In Index:  To bind ddl from different table/storeprocedure
 Method 1:

In View:
·        Using ViewBag

@Html.DropDownList("ddllocation", (IEnumerable<SelectListItem>)ViewBag.location,"Select")

  Using  ViewData
@Html.DropDownList("ddlDepartments",ViewData["Locations"] as IEnumerable<SelectListItem>, "Select")


In Controller: index  
Using ViewBag

var pcontent = db.spM_Locations_SelectLocation(0).ToList();
ViewBag.location = new SelectList(pcontent, "ID", "Location");  

or

ViewBag.location = new SelectList(db.spM_Locations_SelectLocation(0).ToList(), "ID", "Location");  

·         Using  ViewData

ViewData["Locations"] = new SelectList(db.spM_Locations_SelectLocation(0).ToList(), "ID", "Location"); 


Method 2:
In View:

     @Html.DropDownList("ddllocation", (IEnumerable<SelectListItem>)ViewBag.location,   "Select")

In Controller: index
               List<SelectListItem> Location = new List<SelectListItem>();
                var pcontent = db.spM_Locations_SelectLocation(0).ToList();
                foreach (var item in pcontent)
                {
                    Location.Add(new SelectListItem
                    {
                        Text = item.Location.ToString(),
                        Value = item.ID.ToString()
                    });
                }

                ViewBag.location = Location;

Method 3:
In View:
      @Html.DropDownList("TopTags", null, new { @onchange =  "ChangeCallback(this.value);" })


<script type="text/javascript">
    function ChangeCallback(value) {
        window.location.href =path; 
    }
</script>

In Controller: index

In controller:
    var data = db.spM_BranchMaster_Select(0).ToList();
    ViewBag.TopTags = new SelectList(data, "BranchID", "BranchName");




Comments

Popular posts from this blog

How to retain the data annotations or class during modify a table in the database

Interview Questions

AJAX CONTROL