DropDownListFor initial value not selected - c#

I don't understand why the initial value is not selected when the form is loaded.
Here's my code
model.LUIsUsed = new List<SelectListItem>()
{
new SelectListItem { Value = "0", Text = "Ignore" },
new SelectListItem { Value = "1", Text = "Required" },
new SelectListItem { Value = "2", Text = "Optional" },
};
In my view
#Html.DropDownListFor(x => x.Foo[i].IsUsed, Model.LUIsUsed, new { #class= "form-control input-sm is-used" })
x.Foo[i].IsUsed value is "1", but required is not selected. I can't figure out why.
Is it because x.Foo is an array?
EDIT: When I don't use an array, it works

It looks like there's a problem with DropDownListFor inside a for loop.
I had to build a SelectList and specify the selected value.
#Html.DropDownListFor(x => x.Criterias[i].IsUsed, new SelectList(Model.LUIsUsed,"Value","Text", Model.Criterias[i].IsUsed))
It works, but I would like to know why.

Related

How to make MVC dropdownlist change editor field value

I have an edit view that implements a normal editor text field. The user can manually enter a value that can be saved to the model. However, alongside this editor field I also need a dropdownlist that the user can select from that will edit the editor field. However, the value I am putting in the editor field is not the same as the value selected from the dropdownlist, this value comes from another list which uses the index of the item selected by the dropdownlist to put the value. To illustrate:
I have a text field "Name Id" and and two lists "Name" and "Id". The user will select a "Name" and the view will place the "Id" into the "Name Id" Field.
Example:
Name Id: 2 <----- 2 was entered because Bob was selected
Name:
Alex
Bob
Carl
Dennis
Note: Don't forget to include JQuery reference for js code.
Razor Code:
#{
var domainsList = new SelectList(new []
{
new SelectListItem { Text = "Please Select", Value = "0", Selected = true },
new SelectListItem { Text = "Alex", Value = "1" },
new SelectListItem { Text = "Bob", Value = "2"},
new SelectListItem { Text = "Carl", Value = "3"},
new SelectListItem { Text = "Dennis", Value = "4"}
}, "Value", "Text");
}
#Html.Editor("NameId", new {#class="form-control"})
#Html.DropDownList("Nameslst", domainsList,new {#class="form-control"})
Js Code
<script>
$(function(){
$('#Nameslst').on('change',function(){
$('#NameId').val($(this).val())
})
})
</script>

How exactly does the selected value of a selectList work?

I need to create a dropdown list and I'm doing this by creating a new SelectList based on a model. Here is how I am trying to do this:
#Html.DropDownListFor(model=>model.SelectedStudio, new SelectList(Model.Studios, "Id", "Name", Model.Studio)
I see from the class signature that the last parameter is object selectedValue. I have now tried many variations, trying to pass a string there, an object, etc. but when I compile the program, the selected value for the dropdown list is never set to what I want.
Can anyone explain how this works?
EDIT: I don't know if this is important, but the Id of Studio is of type ObjectId (from the MongoDB C# Driver)
I think your not setting for the selected value on new SelectList
your code should be
#Html.DropDownListFor(model=>model.SelectedStudio, new SelectList(Model.Studios, "Id", "Name", [Defualt value])
the reason it not give the error becuase it is object. and your setting up your IEnumerable list. so it is object. see the following link
http://msdn.microsoft.com/en-us/library/dd492553(v=vs.118).aspx
Try this:
#Html.DropDownListFor(model=>model.SelectedStudio, new SelectList(Model.Studios, "Id", "Name", Model.Studio.Id)
this is how u keep a value selected in drop down
#Html.DropDownList("statussearch", new List<SelectListItem>
{
new SelectListItem { Text = "text1", Value = "1", Selected = Studio.IsSelected.HasValue ? Studio.IsSelected.Value : false},
new SelectListItem { Text = "text2", Value = "2"},
new SelectListItem { Text = "text3", Value = "3"},
}, "Select Status")
IsSelected is a field in your DB wch states wch value to be selected.
this will work fine for your requirement
#foreach (var value in studios)
{ #Html.DropDownList("statussearch", new List<SelectListItem>
{new SelectListItem { Text =value.prop1, Value = "1" },new SelectListItem { Text = value.prop2, Value = "2"},new SelectListItem { Text = value.prop3, Value = "3"},}, value.proptobeselected)}

Turning bit type into a dropdownlistfor

I have a BIT type in a sql database that I want to turn into a DropDownList.
I pass a model to the page which has an active field. This field is either true or false. I'm adding the ability to modify this column in the database.
Is it possible to create a DropDownListFor that will give them the option of "Active" "Disable" and then return the correct value to the database?
#Html.DropDownListFor(m => m.active, ??)
#Model.active
I have never tried this but how about this:
#Html.DropDownListFor(m=> m.active, new List<SelectListItem>() { new SelectListItem { Text = "Active", Value = "true", Selected = Model.active }, new SelectListItem { Text = "Inactive", Value = "false", Selected = Model.active } })
This solution works great. The only thing I had to change for my code is the "Selected" value if the model value is "False"
#Html.DropDownListFor(m=> m.active, new List<SelectListItem>() { new SelectListItem { Text = "Active", Value = "true", Selected = Model.active }, new SelectListItem { Text = "Inactive", Value = "false", Selected = !Model.active } })
It was displaying Active even though it should display Inactive.

how to add a selectlistitem to a selectlist

I have the following select list
public SelectList StaffList { get; set; }
I am assigning it the following,
inspectorCorrespondences.StaffList = new SelectList(userDetails, "Id", "FullName");
but I want to add in another SelectList item
var systemGeneratedUser = new SelectListItem() { Value = "-1", Text = "System Generated" };
how do I do that?
This isn't necessarily the most elegant solution, but you'll need to cast the SelectList's items to a list of SelectListItems if you want to add another SelectListItem.
var myItems = new List<SelectListItem>();
myItems.Add(new SelectListItem() { Text = "AA", Value = "11" } );
var mySelectList = new SelectList(myItems);
((List<SelectListItem>)mySelectList.Items).Add(new SelectListItem() { Text = "BB", Value = "22" });
According to the documentation, it looks like you need to initialize the SelectList with the values instead of adding them. Passing an enumerable of SelectListItem to the constructor appears to be the expected way.
It looks like you're already doing that in the sense that userDetails is already an enumeration? If so, what type of enumeration is it? You may need to add a line or two of code to transform it to an enumeration of SelectListItem objects, add yours to that, and then use that to initialize the SelectList. Maybe something like this:
var listItems = userDetails.Select(u => new SelectListItem { Value = u.Id, Text = u.FullName }).ToList();
listItems.Add(new SelectListItem() { Value = "-1", Text = "System Generated" });
// or perhaps .Insert() at position 0 instead?
inspectorCorrespondences.StaffList = new SelectList(listItems, "Value", "Text");

DropDownListFor with an item value 0 always selected

I have a problem getting asp.net and the razor engine to create a drop down list with the correct element selected. No matter what I try, if one of the values available is "0", that item will always be selected.
What I am trying to create is a select for a rating that span from -2 to 2, with 0 being the middle value, but that should NOT be pre-selected. The user should be forced to make a decision and therefore the defualt value should be empty.
Creating the dropdownlist with an option label like the code below shows does not leave the default as empty. This would work if the values were 1-5 for instance.
#Html.DropDownListFor(model => model.Rating, new SelectList(new List<SelectListItem>()
{
new SelectListItem() {Text = "-2", Value = "-2"},
new SelectListItem() {Text = "-1", Value = "-1"},
new SelectListItem() {Text = "0", Value = "0"},
new SelectListItem() {Text = "1", Value = "1"},
new SelectListItem() {Text = "2", Value = "2"}
}, "Value", "Text"), String.Empty, new { #class = "rating-select" })
The above code adds a selected tag to the 0-item and creates the following html:
<select class="rating-select valid" data-val="true" data-val-number="The field Rating must be a number." data-val-required="Rating is required." id="Rating" name="Rating">
<option value=""></option>
<option value="-2">-2</option>
<option value="-1">-1</option>
<option selected="selected" value="0">0</option>
<option value="1">1</option>
<option value="2">2</option>
</select>
I have tried all versions of selecting a blank value, but all result in the same; the 0-item gets generated with a selected tag.
Creating a blank item with Selected = true
#Html.DropDownListFor(model => model.Rating, new SelectList(new List<SelectListItem>()
{
new SelectListItem() {Text = "Null", Value = "", Selected = True},
new SelectListItem() {Text = "-2", Value = "-2"},
new SelectListItem() {Text = "-1", Value = "-1"},
new SelectListItem() {Text = "0", Value = "0"},
new SelectListItem() {Text = "1", Value = "1"},
new SelectListItem() {Text = "2", Value = "2"}
}, "Value", "Text"), String.Empty, new { #class = "rating-select" })
Creating a blank item object and setting the object as selected in selectlist
#{SelectListItem blankItem = new SelectListItem() {Text = "Null", Value = ""}}
#Html.DropDownListFor(model => model.Rating, new SelectList(new List<SelectListItem>()
{
blankItem,
new SelectListItem() {Text = "-2", Value = "-2"},
new SelectListItem() {Text = "-1", Value = "-1"},
new SelectListItem() {Text = "0", Value = "0"},
new SelectListItem() {Text = "1", Value = "1"},
new SelectListItem() {Text = "2", Value = "2"}
}, "Value", "Text", blankItem), String.Empty, new { #class = "rating-select" })
None of the above work when one of the values is 0.
Does anyone know of a proper solution or if this is a bug in the framework?
I can solve it with a work-around hack, but I'd rather not...
I would look at what the type of the model.Rating property is, I am assuming it is an int. If this is an (int) type and you are not providing a value, it will be bound to a 0 when it comes across to a view. As such, when the view is processed, 0 will be marked as selected, that is what the view engine thinks the right value is and will override the selected value that you manually chose. Try making the model.Rating property a nullable int (int?) and see if you have the same issues.
Secondly, you could always look into a quick jQuery function to reset the drop-down to the first provided value, but that might be a little more "hacky" than what you are looking for.
The solution is to either avoid an item having 0 as value because Rating is an int (with default value equal 0), or, handle binding of DropdownList yourself by using Html.DropDownList instead. If you choose latter, you also have to specify Selected for the item user has selected while binding it.

Categories