Set dropdown item selected MVC - asp.net-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());

Related

Fill a DropDownList in .net

I write this code to extract specific column to be added into the list, but its wrong. I want to:
List<Stone_Names> Stones = new List<Stone_Names>();
using (PSPlatformEntities1 p = new PSPlatformEntities1())
{
Stones.Add(new SelectListItem
{
Text = p.Stone_Names["stoneName"].ToString(),
Value = p.Stone_Names["nameID"]
});
}
It's very simple get the list from db first the bind into dropdown
ViewBag.DDlist= db.Stones.ToList().Select(x => new
SelectListItem()
{
Text = x.stoneName,
Value = x.nameID.ToString()
});
In view
#Html.DropDownListFor(model => model.modelProperty,
new SelectList(ViewBag.DDlist, "Value", "Text"),
"Select value", new { #class = "form-control" })
Note: stoneName , nameID should be your table name

how to insert dropdown selected value into database

i have one dropdownlist this value coming from another table so in this dropdown selected value insert into another table
see our image
<div class="col-lg-4">
<fieldset class="form-group">
#Html.LabelFor(model => model.CompanytypeID, new { #class = "form-label semibold" })
#Html.DropDownList("CompanyType", null, "--- Select CompanyType Name ---", new { #class = "select2-arrow" })
#Html.ValidationMessageFor(model => model.CompanytypeID, "", new { #style = "color:red" })
</fieldset>
</div>
public void CompanyType_Bind()
{
DataSet ds = dDSP.Get_CompanyType();
List<SelectListItem> companylist = new List<SelectListItem>();
foreach (DataRow dr in ds.Tables[0].Rows)
{
companylist.Add(new SelectListItem { Text = dr["CompanyType"].ToString(), Value = dr["CompanytypeID"].ToString() });
}
ViewBag.CompanyType = companylist;
}
public DataSet Get_CompanyType()
{
SqlCommand cmd = new SqlCommand("Select * From UserType", constr);
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
da.Fill(ds);
return ds;
}
Error page
Your SELECT element name should match with your property name. With your current code, you are generating a select element with name "CompanyType", But in your view model(Department) your property name is CompanyTypeId.
For model binding to work, the input element name should match with the property name. So use the same name for your SELECT element and you should be good.
#Html.DropDownListFor(x=>x.CompanyTypeId, ViewBag.CompanyType as List<SelectListItem>,
"Select CompanyType", new { #class = "select2-arrow" })
Going further, do not post link to images of your code. Instead include the relevant code in the question itself.
You haven't tied your the dropdown for your code to any property of your Department model.
#Html.DropDownList("CompanyType", null, "--- Select CompanyType Name ---", new { #class = "select2-arrow" })
will generate a select element with the name CompanyType.
From your Validator code you can see that you want to tie it to CompanytypeID
Easiest thing to do would be to change you dropdown declaration to DropDownListFor and "bind" it to CompanytypeID
<div class="col-lg-4">
<fieldset class="form-group">
#Html.LabelFor(model => model.CompanytypeID, new { #class = "form-label semibold" })
#Html.DropDownListFor(m => m.CompanytypeID, ViewBag.CompanyType as IEnumerable<SelectListItem>, "--- Select CompanyType Name ---", new { #class = "select2-arrow" })
#Html.ValidationMessageFor(model => model.CompanytypeID, "", new { #style = "color:red" })
</fieldset>
</div>
It would be good to see your entire cshtml page.
I'd also recommend using ViewModels. It looks like you are POST'ing back your entity model which is why your putting this list in a ViewBag.

Get SelectedValue from List<SelectListItem> DDL

If I have a method like this:
public static List<SelectListItem> lstPassFail()
{
List<SelectListItem> lstPossiblePassFail = new List<SelectListItem>()
{
new SelectListItem() { Text = "Pass", Value = "Pass" },
new SelectListItem() { Text = "Fail", Value = "Fail" },
};
return lstPossiblePassFail;
}
Then in my Edit Action I do this:
ViewBag.PassFail = ClassName.lstPassFail();
Then in my Edit View I do this:
#Html.DropDownList("PassFail", (List<SelectListItem>)ViewBag.PassFail, "-- Please Select a Result --", htmlAttributes: new { #class = "form-control" } )
Since this record already exists in the database and that field already has a value how do I display that selectedvalue, instead of the DDL selecting the very first option by default?
I know that you can do this with an overloaded method for SelectList, but can this be done in the way I portrayed above?
Any help is appreciated.
I have figured this out.
I changed:
ViewBag.PassFail = ClassName.lstPassFail();
to
ViewBag.PassFail = new SelectList(ClassName.lstPassFail(), "Value", "Text", chosenWTest.PassFail);
Then in my view I changed the dropdownlist to this
#Html.DropDownList("PassFail", null, "-- Please Select a Result --", htmlAttributes: new { #class = "form-control" } )
This saved the value for that field in that record.

How to show selected value in DropDownList of 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" })

Dropdownlistfor selected item not selecting using viewbag

I have dropdownlistfor which is getting populated from viewbag string array
<td>#Html.DropDownListFor(m => Model[i].start_operation, new SelectList(ViewBag.ValidOpers))</td>
<td>#Html.DropDownListFor(m => Model[i].end_operation, new SelectList(ViewBag.ValidOpers))</td>
It is not selecting the selected item based on Model[i].start_operation and end_operation
ViewBag.ValidOpers = new[] { "One", "Two", "Three", "Four"};
Unable to figure out why it is not selecting. I check giving just a Html.DisplayFor(m=>Model[i].start_operation to check if it is getting the values and yes it is getting the value and displaying correctly in the label, but the same value is not getting selected in the dropdownlistfor.
To over-answer your question:
Try first adding a not-mapped member to your model class:
e.g.
[NotMapped]
static public List<SelectListItem> myListOptions { get; set; }
then in the controller you can have
MyNameSpace.Models.MyModel.myListOptions = db.myTable.Select(uA=> new SelectListItem{ Value = uA.myColumn, Text = uA.myColumn}).Distinct().OrderBy(uA=>uA.Text).ToList();
// if you want string constants use:
MyNameSpace.Models.MyModel.myListOptions = new List<SelectListItem>();
MyNameSpace.Models.MyModel.myListOptions.Add(new SelectListItem() {Text = "a", Value = "a"});
MyNameSpace.Models.MyModel.myListOptions.Add(new SelectListItem() {Text = "b", Value = "b" });
then in the view, you use:
<div class="editor-field">
#Html.DropDownListFor(model => model.myField, MyNameSpace.Models.MyModel.myListOptions )
#Html.ValidationMessageFor(model => model.myField)
</div>

Resources