DropDownListFor not populating selected value - razor

Probably a frequently asked question, but I didn't found any answer matching my problem.
I got a SelectList like, which I want to show in a DropDown:
var selectList = new SelectList(listItems, "Text", "Value", selectedCustomer);
#Html.DropDownListFor(model => model.Name, selectList, "-- Select Customer --")
The list holds the correct values, one is selected. But the dropdownlist shows only the text "-- Select Customer --".
Populating listItems:
List<SelectListItem> listItems = new List<SelectListItem>();
foreach (Customer c in Model.GetAllCustomer())
{
listItems.Add(new SelectListItem { Text = c.Id, Value = c.Name });
}
To clarify my question: The dropdown works fine on most sites (it's in the layout page). But sometimes after a POST request it does not show any selected value. All the provided code is in the layout page.

Related

What is the easiest way to add cities and countries of the world to an HTML5 form? [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 7 years ago.
Improve this question
I'm creating a form, and I would like to allow the user to choose their country, and their city. What is the most effective way to do it?
For things like state and country, the possible number is reasonably small enough that you can build dropdowns for this without too much hassle. Here is a plugin for jQuery that has a "country picker" pre-made, and you can easily find the same for State on Google.
When you start talking about cities, there are a vastly large number of them. In my opinion, you're far better off using a simple textbox for this and letting the user fill it in themselves.
EDIT
Here is an example of building a country list from a database in MVC:
Country class (Model)
//This class represents a Country
public class Country
{
public int CountryID { get; set; }
public string CountryName {get; set; }
public Country(int countryID, string countryName)
{
this.CountryID = countryID;
this.CountryName = countryName;
}
}
Controller
List<Country> countries = new List<Country>(); //Create a list of Country objects
IEnumerable<SelectListItem> countryList; //List to hold the values for the dropdownlist
SqlConnection connection = new SqlConnection(connectionString); //build a connection with your connection string
connection.Open();
SqlCommand query = new SqlCommand("SELECT CountryID, CountryName FROM Country", connection); //query the table
query.CommandType = CommandType.Text;
SqlDataReader reader = query.ExecuteReader(); //execute the query
while (reader.Read()) //read out the results, set each result to a Country object
{
Country country = new Country(
Convert.ToInt32(reader["CountryID"]),
reader["CountryName"].ToString());
countries.Add(country); //add to the initial list
}
connection.Close();
//build the list of <SelectListItem>s to pass to the view
countryList = countries.Select(c => new System.Web.Mvc.SelectListItem
{
Text = c.CountryName,
Value = c.CountryID.ToString()
});
ViewBag.CountryList = countryList; //add the list to ViewBag
And the View
#Html.DropDownListFor(x => x.ID, new SelectList(ViewBag.CountryList, "Value", "Text"), new { #class = "formItem" })
This code hits your database for the list of countries and builds a List<Country> from the SqlDataReader. Then we turn these results into a List<SelectListItem> to pass into the view.
The result is a dropdown list that will always contain whatever records are in your database. If you add/remove items, the list will be representative of this.
The #Html.DropDownListFor(x => x.ID) binds the selected Value to the model's ID property, so you simply select this value on POST. (Note that your model will need to contain an ID property for this to work!
EDIT to emphasize the "fun" of making a city selector:
I really, really advise against trying to build a city selector. Check out the list of cities in Kansas (something I picked at random). I didn't bother to count these, but this is a pretty big list, and that alone is one state in one country in the world.
If you went with a database, you'd easily have thousands of records for the United States alone, and that only leaves you with 195 other countries to build data for.
Perhaps you can find a repository that already has this information available, but the amount of work required to make this happen seems prohibitive.

assign a default placeholder value to a dropdown list menu

I am trying to assign a placeholder value to a drop down menu that holds state abbreviations from an entity model.
This is the example code I have tried, but that is not working, because
#Html.DropDownListFor(m => m.StateID, new SelectList(Model.States, "ID", "Abbreviations", Model.StateID), new { id = "StateID" + Model.ID, data_placeholder = "State" })
When I open the page, the first value that shows is AL for Alabama instead that the word "State"
You can use this overloaded version of DropDownListFor to specify default option :-
#Html.DropDownListFor(m => m.StateID, new SelectList(Model.States,"ID","Abbreviations"),
"State", new { id = "StateID" + Model.Id })
Also, Please note that there is no need to specify Model.StateID again in SelectList constructor because automatic selection of dropdown (selected value) will be taken care by first param i.e. m => m.StateID.

how to bind dropdownlist in view dynamically ? mvc4

I want to replace this code in my view
Code :
<label for="name">Lead Source</label><select name="Lead_Source" id="Lead_Source" rel="2">
<option value="1">News Papers </option>
<option value="2">Internet</option>
<option value="3">Social networking</option>
<option value="4">Others</option>
</select>
I want to replace with Dropdownlist so I will bind data dynamically by I am getting undone by work .
I tried like this:
<label for="name">Lead Source</label> #Html.DropDownListFor(c=>c.Lead_Source, Model.Lead_Source_List,"--Select Source--");
The error i am getting after i replace static code is
CS1928: 'System.Web.Mvc.HtmlHelper<Ibs.Iportal.Iwise.Web.Models.LeadSortModel>' does not contain a definition for 'DropDownListFor' and the best extension method overload 'System.Web.Mvc.Html.SelectExtensions.DropDownListFor<TModel,TProperty>(System.Web.Mvc.HtmlHelper<TModel>, System.Linq.Expressions.Expression<System.Func<TModel,TProperty>>, System.Collections.Generic.IEnumerable<System.Web.Mvc.SelectListItem>, object)' has some invalid arguments
EDIT : I am passing a model to view which contain a Lead_Source_List of enumerable list data
Regards
you should create a view model and make strongly typed view,do something like this in you action:
public ActionResult YourAction(int id)
{
var model = new MyViewModel();
using (var db = new SomeDataContext())
{
// Get the boxer you would like to edit from the database
model.Boxer = db.Boxers.Single(x => x.BoxerId == id);
// Here you are selecting all the available weight categroies
// from the database and projecting them to the IEnumerable<SelectListItem>
model.WeightCategories = db.WeightCategories.ToList().Select(x => new SelectListItem
{
Value = x.WeightCategoryId.ToString(),
Text = x.Name
})
}
return View(model);
}
this chunk is populating select list item:
model.WeightCategories = db.WeightCategories.ToList().Select(x => new SelectListItem
{
Value = x.WeightCategoryId.ToString(),
Text = x.Name
})
and assigned to model
Now use in view this way:
#model MyViewModel
#Html.DropDownListFor(
x => model.Boxer.CurrentWeightCategory.WeightCategoryId,
Model.WeightCategories
)

How to get the value of selectlist in view into controller with or without Json

I can get the value of a dropdownlist this way but i cant get the value of a selectlist item with this code. What i can do to get the value into my controller for my create action.
My Controller Contains :
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Create(Product products, Design designs, Material materials, Color colors, Picture pictures, FormCollection form,EventArgs e)
{
if (Request.Files != null)
{
long prod = Convert.ToInt64(form["Product"]);
pictures.product_id = db.Products.Single(x => x.id == prod).id;
My View Contains :
#Html.DropDownList("Product", new SelectList((System.Collections.IEnumerable)ViewData["Productlist"], "id", "name"), "Please Select Product", new { onchange = "productlist()", style = "width:190px; padding:4px; margin:4px;" })
i can get dropdownlist value but cant get the value of selectlist..
My View Contains : (SelectList)
<select id="Color" style=" width:190px; padding:4px; margin:4px;" onchange="colorlist()">
<option label="Please Select Color" ></option>
</select>
so if im gonna need to use json how can i use it inside create action and in view.
If you want to use the default binding, then you need an argument in your Create action named "Product" of whatever type you are passing (i.e. string). Then when the form POSTs to the action the binder will set that argument value to the option selected at the time of POST.

ASP.Net MVC SelectList not 'Selecting' Correct Item

I have been asked to look at a bug in some ASP.Net MVC code and have a (to me) very odd problem with a SelectList.
The code from the controller to generate the items (a method to return a SelectList, there are 5 in total). Each SelectList is then saved into the ViewData collection.
List<SelectListItem> items = new List<SelectListItem>();
string yesText = "Yes";
string noText = "No";
if (ci.LCID.Equals((int)LanguageCodes.FRANCE))
{
yesText = "Oui";
noText = "Non";
}
SelectListItem yesItem = new SelectListItem();
yesItem.Text = yesText;
yesItem.Value = ((int)MarketingBy.Yes).ToString();
yesItem.Selected = selectedValue != null && selectedValue.Equals(int.Parse(yesItem.Value));
SelectListItem noItem = new SelectListItem();
noItem.Text = noText;
noItem.Value = ((int)MarketingBy.No).ToString();
noItem.Selected = selectedValue != null && selectedValue.Equals(int.Parse(noItem.Value));
items.Add(yesItem);
items.Add(noItem);
return new SelectList(items, "Value", "Text", yesItem.Selected ? yesItem.Value : noItem.Value);
A quick 'quickwatch' at the point of creation suggests everything is ok:
At the point the view is being rendered, the values still look ok. However when the view loads, the first item in the list is always selected. The HTML generated is:
<tr>
<td>Fax</td>
<td>
<select id="MarketingByFax" name="MarketingByFax">
<option value="134300002">Yes</option>
<option value="134300001">No</option>
</select>
</td>
</tr>
(Other values ommitted for clarity).
Any ideas? Or avenues to research? The author is adamant that this was working 'up til last week' (I have no idea either way).
Edit: Code for the view -
<td><%: Html.DropDownList("MarketingByFax", (SelectList)ViewData["MarketingByFaxList"])%></td>
This code looks just horrible in every imaginable aspect (IMHO of course). I have no idea why it doesn't work and I don't want to know. All I can do is to suggest you how to improve it (so you can stop reading this post if you are looking for a solution about why your code doesn't work as I have no freaking idea).
So the first improvement would be to get rid of any ViewData and introduce a view model:
public class MyViewModel
{
public string SelectedValue { get; set; }
public IEnumerable<SelectListItem> Items { get; set; }
}
then I would have a controller action that would populate this view model:
public ActionResult Index()
{
var model = new MyViewModel
{
// I want to preselect the second value
SelectedValue = "No",
Items = new[]
{
new SelectListItem { Value = "Yes", Text = "yeap !" },
new SelectListItem { Value = "No", Text = "nope !" },
}
};
return View(model);
}
and in my strongly typed view I would simply bind the helper to the view model:
<%= Html.DropDownListFor(
x => x.SelectedValue,
new SelectList(Model.Items, "Value", "Text")
) %>
Also if you want to work with some enum types you may find the following extension method useful.
See how easy it is? No more ugly casts with ViewData, no more need to define any lists and specify some complicated conditions, ...
Remark: once again, those are just my 2ยข, you can continue the combat with ViewData if you will.
you can try
<%: Html.DropDownList("MarketingByFax", (IEnumerable<SelectListItem>)ViewData["MarketingByFaxList"])%>
dropdwon has an overload that accepts the enumeration of Selectlist type objects and it sets the value of list automatically depending upon Selected property of selectListItems in the list. for this you have to set
ViewData["MarketingByFaxList"] = items;//where item is IEnumerable<SelectListItem> or List<SelectListItem> as you used in your code