Set the first item's value in DDL (MVC4) to null - asp.net-mvc

I have a DDL in my view and i read items and values of this DDL from DB like this :
ViewBag.ContentGroup = new SelectList(obj.GetContentGrouplist(), "Id", "Name");
I put it in viewbag and i read the viewbag from the view like this :
<div class="editor-label">
#Html.LabelFor(model => model.ContentGroupFKId)
</div>
<div class="editor-field">
#Html.DropDownListFor(x => x.ContentGroupFKId, (SelectList)ViewBag.ContentGroup)
#Html.ValidationMessageFor(model => model.ContentGroupFKId)
</div>
So i need a DDL that the first item of that be null how can i do that?
I tried this but it doesn't work:
#Html.DropDownListFor(x => x.ContentGroupFKId,new SelectList(new List<Object> {new {value = null, text = "Select"} (SelectList)ViewBag.ContentGroup)
Best regards.

I don't think you can. Whatever value you provide is going to be used to generate html in the form of a select list, which doesn't support null. As long as you have a DropDownListFor, it is going to set a value, even if it is empty. The best thing you can do is make the first value a "Please select an item" option and set it to null server side.
There isn't a great way to add the "Please Select" option (at least none that I have seen. People are welcome to correct me though!), but there are a few ways to do it. One would be to create a dummy content group that just has a name and id.
var contentGroups = obj.GetContentGrouplist();
contentGroups.Insert(0, new ContentGroup{Id = "0", Name = "Please select a content group"};
ViewBag.ContentGroup = new SelectList(contentGroups, "Id", "Name");
Or you can create an object (which you would use anywhere you needed this functionality) that just holds a text and value property and then manually add all of your content groups to it, including the empty one.
class DropDownListOption{
public string Text{get;set;}
public string Value{get;set;}
}
then in your code
var contentGroups = obj.GetContentGrouplist();
var options = new List<DropDownListOption>();
options.Add(new DropDownListOption{ Id = "0", Text = "Please select a content group"};
foreach(var group in contentGroups)
{
options.Add(new DropDownListOption{ Id = group.Id, Text = group.Name};
}
ViewBag.ContentGroup = new SelectList(options, "Id", "Name");
Both of these options will work. I like the second option better because you can create a generic method of handling all drop down lists a certain way. You will have to handle ContentGroups with an ID of 0 as being null when the user submits the form, but at least it is a way of tracking it.
If I think of another way ill add it.

Related

Why doesn't Bootstrap Select show selected value when I include a default?

When I have an object with a value set, it is only shown initially if I leave out the "--Select--" parameter.
Any idea why that would be?
#Html.DropDownListFor(m => m.FlightDetails.AirlineId, ViewBag.AirlineList as SelectList, "--Select--", new { #class = "form-control selectpicker", #data_live_search = "true", #id = flight.Id + "AirlineId" })
Server-side:
You should set a default value for third params, look like this (Pay attention to SelectedDefaultValueHere)
var ViewBag.AirlineList = new SelectList(`listOfItemHere`,
"ValueOfDropdownItem",
"TextToDisplay",
SelectedDefaultValueHere);
Or You can set Selected of SelectListItem like this
new SelectListItem()
{
Value = "anyValue",
Text = "AnyText",
Selected = true
};
I found that this was my issue: https://stackoverflow.com/a/52431696/6591937.
I can't set the selected value when creating the SelectList because I'm using the same SelectList in more that one place and they all can have different values.
The way I resolved it in my case was that I passed in "--Select--" and I set the value via javascript (as I'm accessing it only via javascript anyway).

How to use Html.EditorFor for a model property so that it clears out the existing value and takes the new value entered by the user in mvc?

I have a property that is defined in my model as below:
public decimal? Amount { get; set; }
I have a column in my table named as 'Amount' and it can have values for Amount column.
Then I have a view, where I need to have an editor for Amount column. I have it defined as below:
#Html.Editor("Amount", new { htmlAttributes = new { #class = "form-control" } })
My issue is, I want the Editor area, to be empty when the view is rendered, but it is taking the value from database and assigning it in my editor field.
I want user to be able to enter data (Amount) value in the editor field, and then, on my submit button click, I want to pass the new entered data to my controller and override the Amount column in database with the new value entered by user.
My button, is defined as below:
#Html.ActionLink("Submit", "EnterAmount", new { id = Model.ItemID, amount = Model.Amount }, new { #class = "btn btn-primary" })
When I run my code setup, my editor field is not empty, and it's pre filled with the data that is already in the database. I do not need this. I want my editor field to be empty.
2nd - if i clear out the pre filled amount, and enter a new amount, and then n I click my submit button, it's not taking the newly entered data and instead using the same previous data.
How can I get this working?
Thanks!
You have to use:
#Html.Editor
For example:
#Html.EditorFor(model => model.Name, new { htmlAttributes = new { #class = "form-control" } })
ASP.NET Razor - C# and VB Code Syntax

Show tooltip(or title) message on every dropdown list items

I’m using a custom dropdownlist and binding elements dynamically, but here I want to show a tooltip message on every items of dropdown list.
View Code:
#Html.DropDownListFor(m => m.Industry,Model.IndustryList, "All", new { #style = "width:258px;", #class = "drpDown" })
Controller code:
IEnumerable<SelectListItem> IndustryList= EntityModel<T>.Where(m => m.t == “something”).ToList().Select(c => new SelectListItem { Text = t.Name, Value = t.Value);
So let me know is there any way to set title on every option items within select tag.
No, the standard Html.DropDownListFor helper doesn't support setting any attributes on the <option> tags except the standard ones (value and selected). You could write a custom helper to achieve that. You may check this example as well as this one.
I would also probably go for Darin's answer, you need a custom drop down list.
A quick (and dirty) alternative might be to loop through manually and create your select list and set the title value on the option.
On your controller, maybe populate a view model as such (I'm just using an anonymous object as an example):
var SelectListViewModel = new[] {
new {
Text = "One",
Title = "I'm One Title",
Value = "1"
},
new {
Text = "Two",
Title = "I'm Two Title",
Value = "2"
}
};
and in your view:
<select>
#foreach (var item in SelectListViewModel)
{
<option title="#item.Title" value="#item.Value">#item.Text</option>
}
</select>
Not the cleanest, but hopefully might be helpful for someone.

ASP.NET MVC DropDownListFor does not honour SelectListItem.Selected

I am using DropDownListFor to render a dropdown list in a view. Somehow the rendered list does not select the SelectListItem with Selected set to true.
In the controller action:
var selectList = sortedEntries.Select(entry => new SelectListItem
{
Selected = entry.Value.Equals(selectedValue),
Text = entry.Value,
Value = entry.Id
});
return View(new DropDownListModel
{
ListId = id,
SelectList = selectList,
OptionLabel = "Click to Select"
});
In the view:
<%= Html.DropDownListFor(m => m.ListId,
Model.SelectList,
Model.OptionLabel,
new {#class="someClass"}) %>
I have tried the following:
make sure that there is one and only one items with Selected set to true.
remove the option label argument.
remove the HTML attribute object.
use SelectList in DropDownListFor:
Html.DropDownListFor(m => m.ListId,
new SelectList(Model.SelectList, "Value", "Text",
new List<SelectListItem>(Model.SelectList).Find(s => s.Selected)),
new {#class="someClass"})
Any suggestions as to what went wrong?
EDIT:
more information:
This action is a child action, called by another view with HTML.RenderAction
DropDownListFor will always select the value that the listbox is for, so in this case it will look at the value of ListId and make that item in the list selected. If ListId is not found in the list, the first item (or default text) will be selected. If you want a list that selects based on the selected attribute use DropDownList (without the For, in that case you have to name it yourself).
So in your case this would work:
var selectList = sortedEntries.Select(entry => new SelectListItem
{
Text = entry.Value,
Value = entry.Id
});
return View(new DropDownListModel
{
ListId = selectedValue,
SelectList = selectList,
OptionLabel = "Click to Select"
});
I got the same problem on the same model (with the other models in the decision no problem)
Does not work:
#Html.DropDownListFor(o => o.Drivers.ValueListItems.Value, Model.Drivers.ValueListItems, new { size = Model.Drivers.ValueSizeList, Multiple = "multiple" })
Works perfectly, the elements selected:
#Html.DropDownListFor(o => o.Drivers.ValueListItems.ToDictionary(u=>u.Value).Values, Model.Drivers.ValueListItems, new { size = Model.Drivers.ValueSizeList, Multiple = "multiple" })
Try like this:
var selectList = sortedEntries.Select(entry => new SelectListItem
{
Text = entry.Value,
Value = entry.Id
});
return View(new DropDownListModel
{
// The drop down list is bound to ListId so simply set its value
// to some element value in the list and it will get automatically
// preselected
ListId = selectedValue,
SelectList = selectList,
OptionLabel = "Click to Select"
});
and in the view:
<%= Html.DropDownListFor(
m => m.ListId,
new SelectList(Model.SelectList, "Value", "Text"),
Model.OptionLabel,
new { #class = "someClass" }
) %>
There could be one more gotcha: you are trying to change the selected value in a POST action. For example you rendered a form, the user selected some value in the dropdown, submitted the form and in your POST action you do some processing on this selected value and when you redisplay the view you want the drop down list to have some other value selected. In this case you will have to remove the initial selection which is contained in the ModelState or the Html helper will ignore the selected value in the model:
// do this before returning the view and only if your scenario
// corresponds to what I described above
ModelState.Remove("ListId");
The solution for this problem is simpler that we all think...
All we need to do is set the property on the view model for the element that the dropdown is bound to - i.e: ListId = 3 for example
this way when we do this
Html.DropDownListFor(m => m.ListId,
new SelectList(Model.SelectList, "Value", "Text",
new List<SelectListItem>(Model.SelectList).Find(s => s.Selected)),
new {#class="someClass"})
the HtmlHelper will automatically pick up the default value to display on the DropDownList
simples!
Hope it may help you and all the others - like me! - that have lost a lot of time searching for a solution for this apparent issue.

DropDownListFor Not Selecting Value

I'm using the DropDownListFor helper method inside of an edit page and I'm not having any luck getting it to select the value that I specify. I noticed a similar question on Stackoverflow. The suggested workaround was to, "populate your SelectList in the view code". The problem is that I've already tried this and it's still not working.
<%= Html.DropDownListFor(model => model.States, new SelectList(Model.States.OrderBy(s => s.StateAbbr), "StateAbbr", "StateName", Model.AddressStateAbbr), "-- Select State --")%>
I have set a breakpoint and have verified the existence (and validity) of model.AddressStateAbbr. I'm just not sure what I'm missing.
After researching for an hour, I found the problem that is causing the selected to not get set to DropDownListFor. The reason is you are using ViewBag's name the same as the model's property.
Example
public class employee_insignia
{
public int id{get;set;}
public string name{get;set;}
public int insignia{get;set;}//This property will store insignia id
}
// If your ViewBag's name same as your property name
ViewBag.Insignia = new SelectList(db.MtInsignia.AsEnumerable(), "id", "description", 1);
View
#Html.DropDownListFor(model => model.insignia, (SelectList)ViewBag.Insignia, "Please select value")
The selected option will not set to dropdownlist, BUT When you change ViewBag's name to different name the selected option will show correct.
Example
ViewBag.InsigniaList = new SelectList(db.MtInsignia.AsEnumerable(), "id", "description", 1);
View
#Html.DropDownListFor(model => model.insignia, (SelectList)ViewBag.InsigniaList , "Please select value")
If you're doing it properly and using a model--unlike all these ViewBag weirdos--and still seeing the issue, it's because #Html.DropDownListFor(m => m.MyValue, #Model.MyOptions) can't match MyValue with the choices it has in MyOptions. The two potential reasons for that are:
MyValue is null. You haven't set it in your ViewModel. Making one of MyOptions have a Selected=true won't solve this.
More subtly, the type of MyValue is different than the types in MyOptions. So like, if MyValue is (int) 1, but your MyOptions are a list of padded strings {"01", "02", "03", ...}, it's obviously not going to select anything.
Try:
<%= Html.DropDownListFor(
model => model.AddressStateAbbr,
new SelectList(
Model.States.OrderBy(s => s.StateAbbr),
"StateAbbr",
"StateName",
Model.AddressStateAbbr), "-- Select State --")%>
or in Razor syntax:
#Html.DropDownListFor(
model => model.AddressStateAbbr,
new SelectList(
Model.States.OrderBy(s => s.StateAbbr),
"StateAbbr",
"StateName",
Model.AddressStateAbbr), "-- Select State --")
The expression based helpers don't seem to respect the Selected property of the SelectListItems in your SelectList.
While not addressing this question - it may help future googlers if they followed my thought path:
I wanted a multiple select and this attribute hack on DropDownListFor wasn't auto selecting
Html.DropDownListFor(m => m.TrainingLevelSelected, Model.TrainingLevelSelectListItems, new {multiple= "multiple" })
instead I should have been using ListBoxFor which made everything work
Html.ListBoxFor(m => m.TrainingLevelSelected, Model.TrainingLevelSelectListItems)
I also having similar issue and I solve it by as follows,
set the
model.States property on your controller to what you need to be selected
model.States="California"
and then you will get "California" as default value.
I encountered this issue recently. It drove me mad for about an hour.
In my case, I wasn't using a ViewBag variable with the same name as the model property.
After tracing source control changes, the issue turned out to be that my action had an argument with the same name as the model property:
public ActionResult SomeAction(string someName)
{
var model = new SomeModel();
model.SomeNames = GetSomeList();
//Notice how the model property name matches the action name
model.someName = someName;
}
In the view:
#Html.DropDownListFor(model => model.someName, Model.SomeNames)
I simply changed the action's argument to some other name and it started working again:
public ActionResult SomeAction(string someOtherName)
{
//....
}
I suppose one could also change the model's property name but in my case, the argument name is meaningless so...
Hopefully this answer saves someone else the trouble.
I know this is an old question but I have been having the same issue in 2020.
It turns out the issue was with the model property being called "Title", I renamed it to "GivenTitle" and it now works as expected.
From
Html.DropDownListFor(m => m.Title, Model.Titles, "Please Select", new { #class = "form-control" })
to
Html.DropDownListFor(m => m.GivenTitle, Model.GivenTitles, "Please Select", new { #class = "form-control" })
this problem is common. change viewbag property name to other then model variable name used on page.
One other thing to check if it's not all your own code, is to make sure there's not a javascript function changing the value on page load. After hours of banging my head against a wall reading through all these solutions, I discovered this is what was happening with me.
The issue at least for me was tied to the IEnumerable<T>.
Basically what happened was that the view and the model did not have the same reference for the same property.
If you do this
IEnumerable<CoolName> CoolNames {get;set;} = GetData().Select(x => new CoolName{...});}
Then bind this using the
#Html.DropDownListFor(model => model.Id, Model.CoolNames)
The View loses track of the CoolNames property,
a simple fix is just to add .ToList() After dooing a projection (.Select()) ;).
I had the same problem. In the example below The variable ViewData["DATA_ACREDITO_MODELO_INTEGRADO"] has a SelectListItem list with a default selected value but such attribute is not reflected visually.
// data
var p_estadoAcreditacion = "NO";
var estadoAcreditacion = new List<SelectListItem>();
estadoAcreditacion.Add(new SelectListItem { Text = "(SELECCIONE)" , Value = " " });
estadoAcreditacion.Add(new SelectListItem { Text = "SI" , Value = "SI" });
estadoAcreditacion.Add(new SelectListItem { Text = "NO" , Value = "NO" });
if (!string.IsNullOrEmpty(p_estadoAcreditacion))
{
estadoAcreditacion.First(x => x.Value == p_estadoAcreditacion.Trim()).Selected = true;
}
ViewData["DATA_ACREDITO_MODELO_INTEGRADO"] = estadoAcreditacion;
I solved it by making the first argument of DropdownList, different to the id attribute.
// error:
#Html.DropDownList("SELECT__ACREDITO_MODELO_INTEGRADO"
, ViewData["DATA_ACREDITO_MODELO_INTEGRADO"] as List<SelectListItem>
, new
{
id = "SELECT__ACREDITO_MODELO_INTEGRADO"
...
// solved :
#Html.DropDownList("DROPDOWNLIST_ACREDITO_MODELO_INTEGRADO"
, ViewData["DATA_ACREDITO_MODELO_INTEGRADO"] as List<SelectListItem>
, new
{
id = "SELECT__ACREDITO_MODELO_INTEGRADO"
...

Resources