In this example we have shown how to bind dropdownlist mvc asp.net.
In model folder I have created this class
public class Categories
{
public string Name { get; set; }
public int id { get; set; }
public bool IsActive { get; set; }
public string Description { get; set; }
}
In Controller I have created this method
public ActionResult CategoriesList()
{
//get loaction or latitude longitude according to databases
List<Categories> CategoriesCollection = new List<Categories>();
CategoriesCollection.Add(new Categories { id=1, Name = "Electronic", Description = "categories ", IsActive =true });
CategoriesCollection.Add(new Categories { id = 2, Name = "Fashion", Description = "categories ", IsActive = true });
CategoriesCollection.Add(new Categories { id = 3, Name = "Home Decor", Description = "categories ", IsActive = true });
ViewBag.data = new SelectList(CategoriesCollection, "id", "Name");
return View();
}
In View bind the dropdown
@Html.DropDownList("Categories", (IEnumerable<SelectListItem>)ViewData["data"],"Please Select")
If you have to submit form on dropdownlist selected index. You need to fire “change event “in javascript as given below
<script type="text/javascript">
function submitform()
{
document.forms[0].submit();
}
</script>
@using(Html.BeginForm ())
{
@Html.DropDownList("Categories", (IEnumerable<SelectListItem>)ViewData["data"], "Please Select", new {onchange="submitform()" })
No comments:
Post a Comment