Pass back multiple selected value from dropdownlist MVC 5 - c#

I have the following properties
public SelectList ListActivities { get; set; } // Will load all hobbies i,e football, golf etc and will be displayed in a dropdown
public List<string> SelectedActivities { get; set; } // Trying to set with multiple selected values.
This is my view.
<div class="col-lg-11">
#Html.DropDownListFor(m => m.UserDetails.SelectedActivities, Model.UserDetails.ListActivities, "Please Select", new { #class = "form-control", multiple = "multiple", id = "listActivities" })
</div>
The issue I have is when I selected more then one option from the ActivitiesDropdown and press submit on my page and go back to the controller the SelectedActivities is null.
Can one shed some light on this please?

For multi-select you should use Html.ListBoxFor and not a Html.DropDownListFor because Html.DropDownListFor returns a single-selection select element.
So for this to work just change your view to:
<div class="col-lg-11">
#Html.ListBoxFor(m => m.UserDetails.SelectedActivities, Model.UserDetails.ListActivities, "Please Select", new { #class = "form-control", id = "listActivities" })
</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>

MVC Razor drop down list default value is not triggering onchange event

I have a drop down list in c# MVC Razor application that is populated via enum data model object. My issue comes into play when the user selects the drop down the default value is the first value from the model and when it is selected the onchange event is not being triggered. Please see code below:
.net core mvc razor view
<tr>
<td>
<a id="GenderLnk" href="#">Click Here to Update</a><br>
<div id="GenderDiv" style="display:none;">
#using (Html.BeginForm("UpdateGender", "Home", FormMethod.Post))
{
#Html.DropDownListFor(m => m.StudentGender, new SelectList(Enum.GetValues(typeof(Gender))), new { #class = "show", onchange = "this.form.submit();" })
}
</div>
</td>
</tr>
Here is the model property
public Gender StudentGender { get; set; }
public enum Gender
{
Female,
Male,
[Display(Name ="Not Applicable")]
NotApplicable,
Transgender
}
The reason for not triggering the "onChange" function is, it technically does not change any value in the form if user selected the default value in the first attempt. What you can do is provide a value like "please select" as the default value and let the user choose a value in the list.
#Html.DropDownListFor(m => m.StudentGender, new SelectList(Enum.GetValues(typeof(Gender))), "-- Please Select -- ", new { #class = "show", onchange = "this.form.submit();" })
May be you can use this question + answer into consideration as well. Hope this helps.
Get a default NULL value from DropDownList in ASP.NET MVC

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

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.

harvest chosen plugin fails to show validation messages for asp.net mvc dropdown list

I am unable to get validation messages after changing my dropdownlist to chosen dropdown list. Chosen plugin can be found here
Jquery code
$('#SelectedPropertyGroup').chosen();
UI Code
<div>
#Html.DropDownListFor(x => x.SelectedGroup, Model.Groups, "Select Group", new
{
#onchange = "javascript:ValidateApplicationSelection(this, 'Group');",
#placeholder = "Please select a product"
})
</div>
<div>
#Html.ValidationMessageFor(model => model.SelectedGroup, "", new { id = "valGroup" })
</div>
Model Code
[Required(ErrorMessage = "Select Group")]
[DisplayName("Group: ")]
public string SelectedGroup { get; set; }
The client side validation ignores hidden fields by default -- Chosen hides the "real" select element when it applies it's magic. You can change the validator defaults like so:
$.validator.setDefaults({ ignore: ":hidden:not(select)" });
This will set the validator to ignore any hidden fields that aren't select elements.
The default for the ignore is ":hidden"

Categories

Resources