How to show selected value in DropDownList of MVC - asp.net-mvc

Below is my DropDownList in view
<div class="col-xs-8 col-sm-8 col-md-4">
#Html.DropDownList("Status",new List<SelectListItem> { new SelectListItem{ Text="Active", Value = "Active" },new SelectListItem{ Text="InActive", Value = "InActive" }}, new { #class = "form-control" })
</div>
From DB value is coming either as "Active" or "Inactive" and dropdown has already these two value. And from my DB i'm assigning value in ViewBag.IsStatus.
Now suppose my value is coming "InAactive" from DB then how to assign this as Selected value in Dropdown rather than to show First dropdown by default as selected.

It's better to use DropDownListFor if you using MVC. But for your case just create SelectList and pass it to DropDownList. SelectList contructor has overload for selected value:
#{ //theese lines actually should be in controller.
var list = new List<SelectListItem>
{
new SelectListItem
{
Text="Active",
Value = "0"
}
,new SelectListItem
{
Text="InActive",
Value = "1"
}
}
}
//thats your code
<div class="col-xs-8 col-sm-8 col-md-4">
#Html.DropDownList("Status",new SelectList(list, "Value", "Text", ViewBag.IsStatus), new { #class = "form-control" })
</div>

If you have a model with Status property then simply assign this the value to the property (for example in controller):
Model
public class Model
{
public string Status {get;set;}
}
Controller
public ActionResult SomeAction()
{
//the value has to correspond to the Value property of SelectListItems
//that you use when you create dropdown
//so if you have new SelectListItem{ Text="Active", Value = "Active" }
//then the value of Status property should be 'Active' and not a 0
var model = new Model{Status = "Active"}
return this.View(model);
}
View:
#model Model
#Html.DropDownListFor(m=>m.Status,new List<SelectListItem> { new SelectListItem{ Text="Active", Value = "Active" },new SelectListItem{ Text="InActive", Value = "InActive" }}, new { #class = "form-control" })

Related

How to pass value of selected dropdown list from View to Controller in MVC

Hi i need some help on MVC as new in this area. Here is my code for Dropdown list and I just want to get the selected values by user in a controller so that I can pass that value to a table in db. Here is the code from .cshtml
#Html.DropDownList("LogOffTime", new List<SelectListItem>
{
new SelectListItem{ Text="One", Value = "30000" },
new SelectListItem{ Text="Two", Value = "60000" },
new SelectListItem{ Text="Three", Value = "180000" }
}, "Select Time")
Controller:
public ActionResult Index()
{How to get the value from drop down list}
I just need to know how to access the value i.e. the 30000/60000 etc. in controller. Also need to check that no value will be passed if the user does not select anything. Also correct me pls. if anything wrong in my code. Thanks!
I have this example from what I am working right know. I hope it can help
View or DropDownList:
#using(Html.BeginForm("getSelectedValue", "Home", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
#Html.DropDownList("LogOffTime", new List<SelectListItem>
{
new SelectListItem{ Text="One", Value = "30000" },
new SelectListItem{ Text="Two", Value = "60000" },
new SelectListItem{ Text="Three", Value = "180000" }
}, "Select Time")
<input type="submit" value="Submit" />
}
HomeController:
[HttpPost]
public ActionResult getSelectedValue()
{
var selectedValue = Request.Form["LogOffTime"].ToString(); //this will get selected value
}
First of all you need a model.. Lets say you have Id column in your model..
public ActionResult Index()
{
ViewBag.MyList= new SelectList(db.MyTable.ToList(), "Id", "Name");
return View();
}
In Razor
#Html.DropDownListFor(m => m.Id, ViewBag.MyList as SelectList, new { #class = "form-control" })
POST Controller Method
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<ActionResult> Index(MyModel model)
{
int getmyid=model.Id;
}
Create a model
public class dropdown {
public int value {get;set;}
}
You need to add using around your dropdown list like this, Add a submit button which will do a post to the controller-
#using(Html.BeginForm("Index", "Home", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
#Html.DropDownList(m=>m.value,"LogOffTime", new List<SelectListItem>
{
new SelectListItem{ Text="One", Value = "30000" },
new SelectListItem{ Text="Two", Value = "60000" },
new SelectListItem{ Text="Three", Value = "180000" }
}, "Select Time")
<input type="submit" value="Submit" />
}
In your controller
public ActionResult AddItem(dropdown value) // you will get the value here
{
// do something
}
Its very simple you just need to understand only one thing ,For dropdownlist control, view form will post only the selected value along with name of dropdownlist control as a key-value pair to the controller method. So you can simply write like below to get value
View Code:
#Html.DropDownList("LogOffTime", new List<SelectListItem>
{
new SelectListItem{ Text="One", Value = "30000" },
new SelectListItem{ Text="Two", Value = "60000" },
new SelectListItem{ Text="Three", Value = "180000" }
}, "Select Time")
Controller Code:
public ActionResult Index( string LogOffTime) //LogOffTime is name of dropdownlist controll
{
//some logic
}
Note: You should put the ddcontrol inside your form tag, and post the data using the submit or you can also do the same thing with change event of jquery.
Hope the above information was helpful
Thanks
Karthik
SelectLists are one of the more challenging concepts for people (me) to grasp. Part of the confusion is that when we set the "Text", we intuitively think that "Value" is an number (int or "Id"). It's not. "Value" is passed from the view to the controller as a string. Then, when the form is submitted to the controller, you'll want to parse the "Value" and convert the value to an int. See below:
Your viewmodel should have a property of type 'string' that will hold the selected value.
ViewModel
public class dropdown {
public string selectedvalue {get;set;}
}
View
#using(Html.BeginForm("Index", "Home", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
#Html.DropDownListFor(m=>m.selectedvalue, new List<SelectListItem>
{
new SelectListItem{ Text="One", Value = "30000" },
new SelectListItem{ Text="Two", Value = "60000" },
new SelectListItem{ Text="Three", Value = "180000" }
}, "Select Time")
<input type="submit" value="Submit" />
}
Controller
public ActionResult Index(string selectedValue)
{
int value = 0;
bool valueIsInt = Int32.TryParse(selectedValue, out value); //this returns true if selectedValue can be converted to int and outputs the int as "value"
if (valueIsInt)
{
selectedvalue = value // if value is an int, set it to selectedvalue
}
//otherwise do something else
}
I know this is a little late, but hopefully this can help someone struggling with selectlists as I was.

How can I get the selected item from dropdownlist in controller?

#using (Html.BeginForm())
{
#Html.AntiForgeryToken()
#Html.DropDownListFor(model => model.td_company_name, ViewBag.Listcompany as IEnumerable, new { #class = "form-control" }) }
The selected value is bound to the ViewModel property you define in the expression you pass as first parameter to DropDownListFor. In the example you have given this would be td_company_name. To get the selected item, retrieve it from the available options using the selected value.
[HttpPost]
public ActionResult MyPostAction(td_company model) {
var selectedValue = model.td_company_name;
IEnumerable<SelectListItem> availableOptions = Listcompany();
SelectListItem selectedItem = availableOptions.Single(opt => opt.Value == selectedValue);
// ...
}

How to retain the ASP.NET dropdownlist selected item

I'm trying to retain the selected value of a dropdownlist once the user change the dropdownlist item but its not working as expected what I wanted is to retain the selected item in the dropdownlist but its it defaulted to the Select Company everytime i select the item from dropdownlist, once the user change it postback the page (i know there is no postback in the MVC)
What I'm doing wrong here?
<div class="form-group">
#using (Html.BeginForm("Index", "Home", FormMethod.Post, new { #id = "form_dropdown" }))
{
#Html.DropDownListFor(m => m.ListOfCompanies,
new SelectList((System.Collections.IEnumerable)Model.ListOfCompanies, "Value", "Text"),
"Select Company", new { #class = "form-control", Name = "sel" })
}
[HttpPost]
public ActionResult Index(string sel)
{
var vModel = new EmployeeViewModel();
vModel = _db.GetEmployee.ToList();
//load list of companies:
var company = _db.LoadComapny.ToList();
IEnumerable<SelectListItem> result = model.Select(b => new SelectListItem
{
Value = b.Value,
Text = b.Text,
Selected = b.Text == sel
}).ToList();
vModel.ListOfCompanies = company;
vModel.SELECTED_COMPANY = sel;
return View(vModel);
}
Model:
public class EmployeeViewModel
{
public IEnumerable<SelectListItem> ListOfCompanies { get; set; }
public string SELECTED_COMPANY { get; set; }
//other props
}
DropdownListFor has 2 important argumnets:
the first one the variable with the index of the selected item (mostly lambda expressions (=>) were used)
the secound one is the SelectList of items availble
#Html.DropDownListFor(m => m.SELECTED_COMPANY,
new SelectList(Model.ListOfCompanies, "Value", "Text"),
"Select Company", new { #class = "form-control", Name = "sel" })
Update it to
#Html.DropDownListFor(m => m.SELECTED_COMPANY,
new SelectList((System.Collections.IEnumerable)Model.ListOfCompanies, "Value", "Text"),
"Select Company", new { #class = "form-control", Name = "sel" })

DropDownListFor HTML helper not selecting option for Enum model property

I have an ASP.NET MVC 4 site and a domain model that uses an Enum. I'm able to generate a list of SelectListItem objects, but the proper item is not selected.
Domain Model
public enum ApplicationStatus
{
Unknown = 0,
Incomplete = 1,
Submitted = 2,
Error = 4
}
public class Application
{
public ApplicationStatus Status { get; set; }
// ...
}
The "Edit" View
#model Application
#using (Html.BeginForm("Edit", "Applications", new { ... }, FormMethod.Post, new { role = "form", #class = "form-horizontal" }))
{
#Html.Partial("_Form", Model)
<p>
#Html.ActionLink("Cancel", "Details", new { ... }, new { #class = "btn btn-default" })
<button type="submit" class="btn btn-primary">Save</button>
</p>
}
The "_Form" Partial
#model BWE.Models.Entity.BitWeb.Application
#Html.ValidationSummary(true)
<div class="form-group">
#Html.LabelFor(model => model.Status, new { #class = "col-sm-2" })
<div class="col-sm-10">
#Html.DropDownListFor(model => model.Status, SelectHelper.GetApplicationStatusOptions(Model.Status))
#Html.ValidationMessageFor(model => model.Status)
</div>
</div>
SelectHelper
public static class SelectHelper
{
public static IEnumerable<SelectListItem> GetApplicationStatusOptions(ApplicationStatus currentStatus)
{
var items = new List<SelectListItem>()
{
new SelectListItem()
{
Text = "Select",
Value = string.Empty
}
};
IEnumerable<ApplicationStatus> statuses = Enum.GetValues(typeof(ApplicationStatus)).Cast<ApplicationStatus>();
foreach (var status in statuses)
{
if (status == ApplicationStatus.Unknown)
continue;
items.Add(new SelectListItem()
{
Text = status.ToString(),
Value = ((int)status).ToString(),
Selected = status == currentStatus
});
}
return items;
}
}
The "Select" option is always selected in the dropdown even though I can step through the code and see one of the SelectListItem objects get their Selected property set to true.
I've tried the solution recommended in My templated helper using a DropDownListFor does NOT reflect the model of enum. Why?, but this solution was geared towards MVC 3. I tried the solution (passing a SelectList object as the second argument to Html.DropDownListFor) and all I got was a dropdown list with 4 options whose display text was "System.Web.Mvc.SelectListItem" and no values for the <option> tags.
Furthermore, I tried other solutions that created an #Html.EnumDropDownListFor(...) helper function, which behaved the same way. It seems that all though the proper SelectListItem is getting selected, maybe the current Model.Status value is overriding it?
Update #1
I added an integer property called StatusId which gets and sets the Status property as an integer, and this works when calling Html.DropDownListFor(model => model.StatusId, ...) however I was hoping for a solution that allows me to use the enum value directly, not as a proxy through another property.
For some crazy reason, enum values are rendered as their string-based names by Razor, rather than their integer value counterparts. Regardless, my guess is that your SelectHelper is returning options with values as integers, which is why converting your enum value to an int allowed the selection to work. Since this is a custom component you have anyways, I would suggest simply modifying your helper to return the enum string names as the option values instead of ints. Then the property value and the option values will line up properly.

Set dropdown item selected MVC

I have multiple dropdown list for same select list in look and want to set dropdown item selected as per loop.
How can I set specific one item of dropdown list selected in mvc dropdownlist.
Please help.
The Html.DropDownList method takes multiple parameters, one of them being a List<SelectListItem>. The individual instance of the SelectListItem is where you set the Selected property:
var item = new SelectListItem() {
Selected = /* condition */,
Value = "Some Value",
Text = "Some Text"
};
Alternatively:
Create a SelectList collection that exposes the SelectedValue property:
Model.YourSelectList = new SelectList(items /* List<SelectListItem> */,
"Value",
"Text",
37 /* selected value */);
When building the SelectList, you can set the selected item on construction using http://msdn.microsoft.com/en-us/library/dd460123.aspx
Or you can set it on an individual SelectListItem via it's Selected property ( http://msdn.microsoft.com/en-us/library/system.web.mvc.selectlistitem.selected.aspx ) and use the single-parameter constructor of the select list, or pass it straight to the DropDownList method.
Use the HTML helper ListBoxFor.
#Html.ListBoxFor(m => m.MyPropertyId, Model.MySelectList)
To build the list of items, you can use the MultiSelectList. For example, in your controller:
public ActionResult Index()
{
// Get a collection of all product id's that should be selected.
int[] productIds = _service.GetSomeProductIds();
// Make a new select list with multiple selected items.
ViewBag.List = new MultiSelectList(
_service.Products,
"Id", // Name of the value field
"Name", // Name of the display text field
productIds ); // list of selected product ids
return View();
}
Then in your view:
#Html.ListBoxFor(m => m.ProductIds, (IEnumerable<SelectListItem>)ViewBag.List)
MVC method to bind custom list to dropdownlist and select item dynamically
if you need more details ,comment below
Create Section
#{
List<SelectListItem> list = new List<SelectListItem>();
list.Add(new SelectListItem { Text = "SALE", Value = "SAL" });
list.Add(new SelectListItem { Text = "PURCHASE", Value = "PUR" });
}
<div class="form-group">
#Html.LabelFor(model => model.SaleOrPurchase, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.DropDownListFor(model => model.SaleOrPurchase, list, "-- Select Status --", new {#class= "form-control" })
#Html.ValidationMessageFor(model => model.SaleOrPurchase, "", new { #class = "text-danger" })
</div>
</div>
EDIT Section
List<SelectListItem> list = new List<SelectListItem>();
list.Add(new SelectListItem { Text = "SALE", Value = "SAL" });
list.Add(new SelectListItem { Text = "PURCHASE", Value = "PUR" });
IEnumerable<SelectListItem> myCollection = list.AsEnumerable();
ViewBag.SaleOrPurchase = new SelectList(myCollection, "Value", "Text", transactionTbl.SaleOrPurchase.ToString().Trim());

Resources