ASP.NET MVC Dropdown List from Selectlist

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.

DropDownList - How to add SelectListItem ASP.NET MVC

This two Post helped me out to solve the problem and Thanks to @Stephen Muecke with his good post, Which is wroted Here and Thanks to this post with great explanation, which is wroted Here.

Here is what i did , maybe it helped someone one day :) :

Add To Property to my View Model :

public class VMRMA
{
public List<SelectListItem> Status { set; get; }

public int? SelectedStatus { set; get; }
}

Change my ActionResult to :

public ActionResult RMA (int Id)
{
VMRMA model = new VMRMA();

model.Status = new SelectList(DatabaseNameSpace.RMAStatus, "ID",
"Status").ToList();
//some an other stuff

return View(model);
}

and than change my View to :

@Html.DropDownListFor(s => s.SelectedStatus, Model.Status, "- Select -", new { @class = "form-control" }) 

How to correctly use Html.DropDownList with SelectList?

The code you have for the anchor tag has some C# code, which gets executed on the server. Since the user can change the selected option of dropdown to something else at client side, you should handle this with client side javascript.

So set the href value of your link to the base url of the action method (without the route values) and give it an id which we will use to wire up some client side behavior.

@:<a id="myLink" href="@Url.Action("RoleHandler","Account")">Search Building</a>

Now have some javascript code to listen to the click event on this link, get the selected option from the dropdown and use that to build the new url.

@section scripts
<script>
$(function () {

$("#myLink").click(function (e) {
e.preventDefault();
var url = $(this).attr("href");
url = url + "?RESPONSIBILITY_ID ="+$("#RoleList").val();
window.location.href = url;
});

});
</script>
End Section

Also, you don't really need to create a new SelectList object, you can pass the list of SelectListItem to your DropDownList helper method.

Dim list = New List(Of SelectListItem)() From {
New SelectListItem() With {
.Value = "a",
.Text = "a"
},
New SelectListItem() With {
.Value = "b",
.Text = "b"
}
}

and

@Html.DropDownList("RoleList", list, "Select Role") 

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.

MVC C# Dropdown list Showing System.Web.SelectListItem on the model and can not blind to controller

Follow below technique in which populate your SelectList from your controller. Its simple and clean:

Model

public string KeywordOptionsSelected { get; set; }
public SelectList KeywordOptions { get; set; }

Controller

model.KeywordOptions = new SelectList(new List<SelectListItem> { 
new SelectListItem { Value = "TEST 1", Text = "Market Cap" },
new SelectListItem { Value = "TEST 2", Text = "Revenue" },
}, "Value", "Text");

View

@Html.DropDownListFor(model => model.KeywordOptionsSelected, Model.KeywordOptions, "--Select Option--", new { @id = "Dropdown_TEST" })

In this way, the code is easy to understand and View is also clean as all SelectList will be populated from cs.

You can make it more cleaner by populating SelectLists separately in methods and call in model.KeywordOptions to populate it.

public static List<SelectListItem> GetKeywords()
{
var keyword = new List<SelectListItem>();
keyword.Add(new SelectListItem { Value = "TEST 1", Text = "Market Cap" });
keyword.Add(new SelectListItem { Value = "TEST 2", Text = "Revenue" });
return keyword;
}
model.KeywordOptions = new SelectList(GetKeywords(), "Value", "Text");

asp.net MVC - using list of strings in a DropDownListFor

You can generate a collection of SelectListItems from the list of strings and use that with DropDownListFor helper method.

var names = new List<string> {"Adam", "Sam"};
ViewBag.Names = names.Select(f => new SelectListItem() {Value = f, Text = f});

and in the view

@Html.DropDownListFor(f=>f.Name, ViewBag.Names as IEnumerable<SelectListItem>, 
"select one")


Related Topics



Leave a reply



Submit