How to Get This ASP.NET MVC Selectlist to Work

Unable to get SelectList working in ASP.NET MVC

Here is a step by step explanation of using DropDownListFor helper in your case.

  1. Create a model which will contain a collection of SelectListItem instances.

    public class MyModel
    {
    public List<SelectListItem> TaxIDType = new List<SelectListItem>()
    {
    new SelectListItem() { Text = "FEIN", Value = "FEIN" },
    new SelectListItem() { Text = "SSN", Value = "SSN" }
    };
    }

Note: if you want, you can even make the property static, however, you will need to change the way you reference the property on the view (will explain it eventually)


  1. Create the model and pass it to the view.

    public ActionResult Index()
    {
    var viewModel = new MyModel();
    return View(viewModel);
    }
  2. In the view, state that your view uses MyModel class. You can do it by putting the @model helper on the top of your view (.cshtml file).

     @model WebApplication3.Controllers.MyModel 

Here, WebApplication3.Controllers is a namespace of your model and MyModel is it's name. Don't use the listed namespace and model, but change them to your own.


  1. Use the DropDownListFor helper as following

     @Html.DropDownListFor(x => ??, Model.TaxIDType)

In the example, Model is a property which is being populated by the framework to let your acecss a class instance which you passes in View() method inside the controller. (MyModel instance in this case).
By writing Model.TaxIDType you are referencing the property which contains the list of items to poppulate the dropdown.
Notice, that the property in the model isn't marked as static, that's why we have to access it via the instance (Model) reference. However, you can, indeed, make the property static. In that case, you will need to change the usage in the view to the following:

     @Html.DropDownListFor(x => ??, MyModel.TaxIDType)

The last thing to mention: take a look at the question marks. In order to get the selected value back, you will need to map it to the model. One way to do it is to extend the model.

public class MyModel
{
public string SelectedTaxIdType { get; set; }

public List<SelectListItem> TaxIDType = new List<SelectListItem>()
{
new SelectListItem() { Text = "FEIN", Value = "FEIN" },
new SelectListItem() { Text = "SSN", Value = "SSN" }
};
}

and than modify the view

@Html.DropDownListFor(x => x.SelectedTaxIdType, Model.TaxIDType)

ASP.NET MVC SelectList doesn't select value on creation

I turns out that this question had the answer:
Html.DropdownListFor selected value not being set

I have it changed in the code posted above, and it wasn't working, but a clean and rebuild solved the problem. Originally the ViewBag property was named "Title", the same as the model property.

Thanks for the help.

ASP.NET MVC Dropdown List From SelectList

You are missing setting the Text and Value field in the SelectList itself. That is why it does a .ToString() on each object in the list. You could think that given it is a list of SelectListItem it should be smart enough to detect this... but it is not.

u.UserTypeOptions = new SelectList(
new List<SelectListItem>
{
new SelectListItem { Selected = true, Text = string.Empty, Value = "-1"},
new SelectListItem { Selected = false, Text = "Homeowner", Value = ((int)UserType.Homeowner).ToString()},
new SelectListItem { Selected = false, Text = "Contractor", Value = ((int)UserType.Contractor).ToString()},
}, "Value" , "Text", 1);

BTW, you can use a list or array of any type... and then just set the name of the properties that will act as Text and Value.

I think it is better to do it like this:

u.UserTypeOptions = new SelectList(
new List<SelectListItem>
{
new SelectListItem { Text = "Homeowner", Value = ((int)UserType.Homeowner).ToString()},
new SelectListItem { Text = "Contractor", Value = ((int)UserType.Contractor).ToString()},
}, "Value" , "Text");

I removed the -1 item, and the setting of each item selected true/false.

Then, in your view:

@Html.DropDownListFor(m => m.UserType, Model.UserTypeOptions, "Select one")

This way, if you set the "Select one" item and don't set one item as selected in the SelectList, the UserType will be null (the UserType need to be int? ).

If you need to set one of the SelectList items as selected, you can use:

u.UserTypeOptions = new SelectList(options, "Value" , "Text", userIdToBeSelected);

As one of the users explained in the comments:
The 4th option of the SelectList constructor is ignored when binding to a property using DropDownListFor() - it is the property's value that determines what is selected.

SelectList not working (ASP.NET MVC)

You need to use this Html.Action overload which will call the action method and the action will return the partial view back. Html.Partial is just rendering the view as html without calling the action so ViewBag.Region is not having the value which is expected :

@Html.Action("AddProject","Project")

assuming the controller class name is ProjectController.

So what will happen now is that Html.Action will call the AddProject action and will return the ActionResult back to your view from which we have called and will render html of partial view ProjectModalPartial.cshtml

Selected item in SelectList not being displayed in view drop-down

This one has bitten me a few times in the past, all the way back to MVC 3 or so.

Basically, if you're passing a model to your view (i.e. using a @model MyTypeOfViewModel directive) and binding a select to a property on that model, then the selected value of the select list is the value of the property you are binding to on your view model. Setting the selected item in a select list directly will be ignored.

In your case, it's SeasonID from this:

<select asp-for="SeasonID" ...>

So for you to select Season 2, you'd need to set the value of the SeasonID property on your view model to the ID of Season 2:

var viewModel = new SeasonViewModel
{
SeasonID = // Season 2's SeasonID
}

However, if you're not binding the value of the select directly, creating the select like this:

// Notice I've not specified `asp-for`.
<select class="form-control" asp-items="ViewBag.Seasons"></select>

will use the selected value you set when creating the SelectList. That said, your code to do that is currently slightly wrong. It should be:

var selected = _context.Seasons
.Where(s => s.IsCurrent == true)
.FirstOrDefault();
ViewData["Seasons"] = new SelectList(
_context.Seasons,
"ID",
"SeasonName",
// It needs to be the actual value of the field, not the season's object.
selected?.ID.ToString());

In short, if you want to bind to your SeasonID property, create your SelectList, without selecting a value, like so:

ViewData["Seasons"] = new SelectList(
_context.Seasons,
"ID",
"SeasonName");

Then set the selected value on the view model itself, and the asp-for attribute on the select will do the rest.

ASP.NET MVC Dropdown List not selecting

Please modify your model based on below code:-

public class BuyingModel
{
public string SelectedPropertyId { get; set; }
public IEnumerable<SelectListItem> propertyType
{
get
{
return new[]
{
new SelectListItem {Value = "1", Text = "Any" },
new SelectListItem {Value = "2", Text = "Single Family Home" },
new SelectListItem {Value = "3", Text = "Condo"}
};
}
}
}

I have introduced a SelectedPropertyId field to store the selected property type from UI.
Please populate the SelectedPropertyId field while posting back the form.
On the view please render the dropdown like below :-

@Html.DropDownListFor(m => m.SelectedPropertyId, Model.propertyType)

Above code should hopefully fix your issue.

Selected value not working for SelectList

Found the problem.

The mistake I was doing is using this

m => m.SchoolYears // m.SchoolYears in a list of string

When I changed it to this

m => m.SelectedYearId // m.SelectedYearId is an integer property

it worked like a charm, so finally I have this working

@Html.DropDownListFor(m => m.SelectedYearId, new SelectList(Model.SchoolYears, "YearId", "StartDates", Model.CurrentYearId), new { @class = "field_Dropdown", style = "width:100px;",onchange="return searchStudents();" })

Thanks!

MVC SelectList not working

The constructor method you're calling when you do:

SelectList selectList = new SelectList(items);

Creates a set of SelectListItems that themselves point to SelectListItems (hence the weird option since it just calls ToString on the object). Instead set your list to the ViewData key directly

ViewData["OrderTypeList"] = items;


Related Topics



Leave a reply



Submit