Razor Html.DropDownListFor automatically set the selected value - c#

I am new to Razor, I pass dropdown list as a viewbag and another values, when drop down list show in web it has selected values but i haven't set the any selected value, I think I use same name in viewbag value and dropdownlist value,it can be happen?
This is the viewbag,here i set the values and drop downlist:
ViewBag.GlobalInstance = globalInstance;
ViewBag.LegislativeCode = legislativeCode.Trim();
ViewBag.Legislatives = new SelectList(legislativeEntities, "LegislativeCode", "LegislativeName");
This is frontend code:
#if (ViewBag.GlobalInstance == true)
{
<div class="col-xs-5 hcm-form_controller mandatory gap" >
<label for="LegislativeCode" class="w-100" mi-resourcekey="atr-LegislativeCode" >Legislative Entity</label>
#Html.DropDownListFor(m => m.LegislativeCode, ViewBag.Legislatives as SelectList, "--- Select ---", new { #class = "calc-w-100" })
</div>
}

It seems that the page model has a value for LegislativeCode,
m => m.LegislativeCode
so when there is a same LegislativeCode in the ViewBag.Legislatives, this option will be selected.

Related

How to set default value for ASP.NET MVC DropDownList from ViewBag

In the controller Index I have the following:
ViewBag.Assignees = (await GetAllUsers()).Select(a =>
new SelectListItem
{
Text = a.DisplayName,
Value = a.Username,
Selected = a.DisplayName == "John Smith"
}).OrderBy(x => x.Text).ToList();
In the View, I have the following:
#Html.DropDownListFor(model => model.Assignee,
ViewBag.Assignees as List<SelectListItem>,
"Select Assignee",
new { id = "ddlAssignee", #class = "form-control"})
The dropdownlist populates as expected, however, the default (selected = true) value, which does exist, does not get set. Can someone advise what is wrong in the above?
UPDATE:
By Changing the SelectListItem.Value to a.DisplayName (same as SelectedListItem.Text) I achieved it. Still not sure what prevents the dropdownlist from displaying the item with Selected = true
If the model.Assignee comes with value, and if it is an int it will be defaulted to 0, it will override the SelectListItem selected value.
I suggest to set up the model.Assignee.
Here two ways that i use.
WAY 1
#Html.DropDownListFor(model => model.Assignee,
ViewBag.Assignees as List<SelectListItem>,
"Value", // property to be set as Value of dropdown item
"Text", // property to be used as text of dropdown item
"1"), // value that should be set selected of dropdown
new { id = "ddlAssignee", #class = "form-control"})
WAY 2
<select name="SelectName" value="1" class="w-100">
#foreach (var item in ViewBag.Collection) {
<option value="#item.Id">#item.Name</option>
}
</select>
I hope it work for you
#Html.DropDownListFor how to set default value
In your view set:
#Html.DropDownListFor(model => model.Assignee,
ViewBag.Assignees as List<SelectListItem>,
"Select Assignee",
new { id = "ddlAssignee", #class = "form-control", #value = "Default value"})
When you have list already defined.
Use This
#Html.DropDownList("CoverageDropDown", new SelectList(Model.youList, "Code", "Description",item.seletecItem), "Select")

asp.net MVC set default value for dropdown list

I'm displaying a dropdown list for countries, which is populated from a database call in the controller. On page load I would like the selected value to default to 'United States'. How do I do this?
Code from view:
<div class="form-group">
#Html.LabelFor(m => m.Country)
#Html.DropDownListFor(m => m.Country, new SelectList(Model.CountriesDDL, "CountryCode", "Country"), "--Select--", new { #class = "form-control" })
</div>
In your GET action, you can set the value of Country property to the CountryCode of United states (or whatever country you want to set as default) of your view model
public ActionResult Show()
{
var vm = new YourViewModel();
vm.CountriesDDL = GetCountriesFromSomeWhere();
vm.Country="United States";
return View(vm);
}
Assuming Country is of type string

How to get disabled DropDownList control value to controller

Work on asp.net mvc5.My project DropDownList work perfectly problem arise when i disabled DropDownList control then can not get value in controller.
My razor syntax is bellow:
<div class="form-group">
#Html.LabelFor(m => m.ProductName, new {#class = "col-md-3 control-label"})
<div class="col-md-3">
#Html.DropDownList("ProductID", null, "Select product", new {#placeholder = "Select product", #class = "form-control", #disabled = "disabled" })
</div>
</div>
my controller syntax to fill the above DropDownList
private void LoadProductsInViewData(object selectedValue = null)
{
var datas = productRepository.GetAll().OrderBy(p => p.Name);
ViewBag.ProductID = new SelectList(datas, "ProductID", "Name", selectedValue);
}
Why In controller create/edit event can not get the DropDownList value?
Note:I know it's disabled control default behavior,i try to use hidden column like this.Problem is how hidden column used with my approach.
You can use Jquery to retrive the value of Currently Selected item of DropList which is disabled in your case, using
var dropDownValue=("#Id_of_u_Dropdownlist").val()
and you can send the DropDownValue variable which contains value of Disable Dropdown list to Controller.
This is a normal behavior. Disabled fields cannot be posted, then it's a common pratice to add a Html.HiddenFor() to post the disabled value.
As you said, there is no "ProductId" property in your model. However, if you create a Html.Hidden("ProductId", "YourValue") and add a parameter named 'productId' in your Controller Create/Edit action, the value should be subimitted.
Create an Httpost Action and then use FormCollection Object like this
[HttpPost]
public ActionResult GetDropDownValue(FormCollection Form)
{
string dropdownValue=form["ID_of_dropdownlist"].toString();
}

Set Dropdown value to null when Page Loads MVC

I have created a DropDwonList in MVC like this
#Html.DropDownListFor(x => x.Item2.DeliveryDetail.PackageTypeId, new SelectList(lstPackageTypes, "PackageTypeId", "PackageTypeName"),new {#class = "cstm-input", #placeholder = "Package Type"})
It generates a DropDown but by default the first Item is selected when page loads. I want that the dropdown should be un-selected and the user should be allowed to select a value from it.
Thanx in Advance.
You can specify the default OptionLabel with overload method of DropDownListFor as below:
#Html.DropDownListFor(x => x.Item2.DeliveryDetail.PackageTypeId,
new SelectList(lstPackageTypes, "PackageTypeId", "PackageTypeName"),
"--Select Package Type--",
new {#class = "cstm-input", #placeholder = "Package Type"})

Setting the default value of an enum dropdown in Razor

I'm trying to create an Item edit screen where the user can set a property of the Item, the ItemType. Ideally, when the user returns to the screen, the dropdown would display the ItemType already associated with the Item.
As it is, regardless of what the item.ItemType is, the dropdown will not reflect that in the dropdown. Is there a way around this?
For reference, my code at the moment is:
<div class="form-group">
#Html.LabelFor(model => model.ItemType, new { #class = "control-label col-xs-4" })
<div class="col-xs-8">
#Html.DropDownListFor(model => model.ItemType, (SelectList)ViewBag.ItemType, new { #class = "form-control" })
#Html.ValidationMessageFor(model => model.ItemType, String.Empty, new { #class = "text-danger" })
</div>
</div>
The ViewBag is set with the following:
var ItemType = Enum.GetValues(typeof(ItemType));
ViewBag.ItemType = new SelectList(ItemType);
If you're using ASP.NET MVC 5, try just using the EnumHelper.GetSelectList method. Then you don't need ViewBag.ItemType.
#Html.DropDownListFor(model => model.ItemType, EnumHelper.GetSelectList(typeof(ItemType)), new { #class = "form-control" })
If not, you might need to specify the data value and data text fields of the select list.
var itemTypes = (from ItemType i in Enum.GetValues(typeof(ItemType))
select new SelectListItem { Text = i.ToString(), Value = i.ToString() }).ToList();
ViewBag.ItemType = itemTypes;
Then since it's an IEnumerable<SelectListItem> you'll need to change your cast.
#Html.DropDownListFor(model => model.ItemType, (IEnumerable<SelectListItem>)ViewBag.ItemType, new { #class = "form-control" })
Eventually I found a fix - manual creation of the list.
<select class="form-control valid" data-val="true"
data-val-required="The Item Type field is required." id="ItemType" name="ItemType"
aria-required="true" aria-invalid="false" aria-describedby="ItemType-error">
#foreach(var item in (IEnumerable<SelectListItem>)ViewBag.ItemType)
{
<option value="#item.Value" #(item.Selected ? "selected" : "")>#item.Text</option>
}
</select>
Try to keep as much of the logic outside of the View and in the Controller.
I saw in your self answer that it looks like you have an enum selected from wihin your controller.
I have a DropDownList in one of my apps that contains a list of Enums. It also has a default value selected, but also has specific enums available to the user. The default selection can be set from within the controller.
This example is based on what my needs were, so you'll need to adapt to your case.
In the controller:
public ActionResult Index()
{
ViewBag.NominationStatuses = GetStatusSelectListForProcessView(status)
}
private SelectList GetStatusSelectListForProcessView(string status)
{
var statuses = new List<NominationStatus>(); //NominationStatus is Enum
statuses.Add(NominationStatus.NotQualified);
statuses.Add(NominationStatus.Sanitized);
statuses.Add(NominationStatus.Eligible);
statuses.Add(NominationStatus.Awarded);
var statusesSelectList = statuses
.Select(s => new SelectListItem
{
Value = s.ToString(),
Text = s.ToString()
});
return new SelectList(statusesSelectList, "Value", "Text", status);
}
In the view:
#Html.DropDownList("Status", (SelectList)ViewBag.NominationStatuses)
This approach will automatically set the default item to the enum that was selected in the controller.

Categories

Resources