set a local variable as selected value - c#

I want to set a local variable as selected in a dropdownlist but it is not working for me.
Here my code :
#{
List
<SelectListItem>
dateEcheancier = new List
<SelectListItem>
();
foreach (var dateEch in arrayDateEcheancier)
{
dateEcheancier.Add(new SelectListItem() { Text = dateEch, Value = dateEch });
}
<div id="md-select-forcage" class="md-select px-0" style="min-width:0px">
#Html.DropDownList("DateEche", new SelectList(dateEcheancier, "Value", "Text", (Selected .ToString())), new { #class = "form-conrol" })
</div>
}
And selected value it is a local variable in my code :
string Selected = ech.Value[i];
Selected = arrayMontantsIds[0];
Note that when i add a selected value like this "20/01/2019" a date in my select list it is working so how i solve this problem

You can use ViewBag
in your controller, set the value as below
ViewBag.Selected=arrayMontantsIds[0];
in your view
<div id="md-select-forcage" class="md-select px-0" style="min-width:0px">
#Html.DropDownList("DateEche", new SelectList(dateEcheancier, "Value", "Text",ViewBag.Selected) , new { #class = "form-conrol" })
</div>

Related

hide/unhide dropdown list in ASP.NET MVC using C# after selection

I have two dropdown lists, one is shown and the other one is hidden by default. I want my 2nd dropdown to be shown only after a particular value is selected from the first dropdown.
My first dropdown - All Items, Document Type
When "Document Type" is selected, 2nd dropdown will appear which is bound from a particular table in the database.
First Drop down
#Html.DropDownList("rptOption", new List<SelectListItem>
{
new SelectListItem { Text = "Document Type", Value = "DocTyp" },
new SelectListItem { Text = "All Items", Value = "allItems" },
}, "--Select--", new { style = "width:250px; height:40px" })
2nd Dropdown which I set hidden by default.
<div id="doctype" hidden="hidden">
#Html.LabelFor(model => model.tfl_idoctype, "Document Type", htmlAttributes: new { #class = "control-label col-md-2" })
#Html.DropDownList("tfl_idoctype", null, htmlAttributes: new { #class = "form-control" })
#Html.ValidationMessageFor(model => model.tfl_idoctype, "", new { #class = "text-danger" })
</div>
When the user selects "Document Type" from the first dropdown, that's the only type that the 2nd drop down will show.
You could do this is in javascript
<script>
// Get the first dropdown element
var firstDropdown = document.getElementById('rptOption');
// Get the second dropdown element
var secondDropdown = document.getElementById('doctype');
// Bind an event handler to the change event of the first dropdown
firstDropdown.addEventListener('change', function() {
// Check the selected value of the first dropdown
if (this.value === 'DocTyp') {
// If the selected value is 'DocTyp', show the second dropdown
secondDropdown.hidden = false;
} else {
// Otherwise, hide the second dropdown
secondDropdown.hidden = true;
}
});
</script>

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")

preselect dropdown list razor page

I have the below code that I use to populate my dropdown in my Razor Page
I want to preselect a description - the "Value" of that needs to be set is found in
s.UserEstablishmentId
How can I preselect this on the dropdown
#Html.DropDownList("drpEstablishments",
getEstablishments().Select(s => new SelectListItem()
{
Text = s.Description,
Value = s.EstablishId.ToString()
}),
new
{
#class = "dropdown form-control"
})
You're using linq to create a new SelectListItem for getEstablishments element. When creating each instance of a SelectListItem() you need to determine if Selected should be true or false. Simply replace YourConditionForSelectionHere with a method that returns a bool or syntax that returns a bool, shown below:
#Html.DropDownList("drpEstablishments",
getEstablishments().Select(s => new SelectListItem()
{
Selected = (YourConditionForSelectionHere),
Text = s.Description,
Value = s.EstablishId.ToString()
}),
new
{
#class = "dropdown form-control"
})
in the end something like this worked
Selected= (s.UserEstablishmentId==s.EstablishId)? true:false,

How to save a dynamic dropdown list in MVC?

I have come across a problem. I am currently attempting to make a users page in which some of the dropdowns are variable and determined by their 'access level'. I then want to save the data from the view into a list and then handle it in the 'Post' controller method. I found this link about a possible solution (Assign selectlist to dynamically created dropdown in MVC) but I am still running into problems.
Here is my controller code I am using to set up the data that needs to generate the dropdowns:
var permData = db.LabPermissions.Where(x => x.AccessLevel == 1).ToList();
//sets up generic dropdown data used for all dropdowns
ViewBag.DropDownData = new List<SelectListItem>
{
new SelectListItem{ Value = "0",Text = "No"},
new SelectListItem{ Value = "1",Text = "Yes"},
};
ViewModel obj = new ViewModel();
obj.DataFromController = permData;
//other viewmodel data
return("MyView",obj);
I then pass the data to my view which looks like this (this is also how the stack overflow link set up the view)
#for(int i = 0; i < Model.DataFromController.Count(); i++)
{
<div class="row">
<div class="col-md-2">
<b>#Html.DisplayFor(m => m.DataFromController[i].Lab.LabName)</b>
</div>
<div class="col-md-2">
#Html.DropDownListFor(m => m.DataFromController[i].Assigner, (SelectList)ViewBag.DropDownData, "Select One")
</div>
<div class="col-md-8">
</div>
</div>
}
After I get this set up, and run the application, this is the error I receive:
Additional information: Cannot convert type 'System.Collections.Generic.List<System.Web.Mvc.SelectListItem>' to 'System.Web.Mvc.SelectList'
And the error is placed on my #Html.DropDownListFor line of code in my view.
Thank you for any help!
Try creating a new selectlist instead and put your selectlistitems in it.
#Html.DropDownListFor(m => m.DataFromController[i].Assigner,
new SelectList(ViewBag.DropDownData, "Value", "Text", "Select One")
Or, since you got a ViewModel you can add a public property that can hold your selectlistitems.
public class ViewModel
{
public IEnumerable<SelectListItem> DropDownData { get; set; }
}
Controller:
var permData = db.LabPermissions.Where(x => x.AccessLevel == 1).ToList();
var vm = new ViewModel();
var list = new List<SelectListItem>
{
new SelectListItem{ Value = "-1", Text = "Select One", Selected = true},
new SelectListItem{ Value = "0",Text = "No"},
new SelectListItem{ Value = "1",Text = "Yes"}
};
vm.DropDownData = list;
vm.DataFromController = permData;
return View(vm);
View:
#model YourNameSpace.Models.ViewModel
#for(int i = 0; i < Model.DataFromController.Count(); i++){
#Html.DropDownListFor(m => m.DataFromController[i].Assigner, Model.DropDownData)
}
I believe that you're trying to cast SelectListItem to SelectList and that is the reason why you're getting that error. I've done the same feature as a part of my project and I'm taking the values for the dropdownlist from the database.
and for displaying, here is my code(modified a bit based on your model variables
My Controller method
public ActionResult GetDropDownList()
{
List<SelectListItem> dropDownList= new List<SelectListItem>();
using (var context = new assessmentEntities())
{
//getting data from the DB
var result = context.getDataFromDB().toList();
foreach (var item in result)
{
dropDownList.Add(new SelectListItem() { Text = item.Variable1, Value = item.Variable2});
}
ViewBag.DropDownData = dropDownList;
}
return View();
}`
Here is my View
#Html.DropDownListFor(m => m.DataFromController[i].Assigner,, new SelectList(ViewBag.DropDownData, "Value", "Text")
Hope so this works for you

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