ASP.Net MVC dropdown selected value - asp.net

I have been dealing with the dropdownlist which i am able to populate but if i come back to edit a record, the dropdown is not showing the selected value.....
In controller,
var datacontext = new ServicesDataContext();
var serviceToUpdate = datacontext.Mapings.First(m => m.CustomerServiceMappingID == id);
var qw = (from m in datacontext.Mapings
where id == m.CustomerServiceMappingID
select m.CustomerID).First();
ViewData["CustomerID"] = qw;
int b = Convert.ToInt32(serviceToUpdate.ServiceID);
var a = datacontext.services.Select(arg => arg.ServiceID).ToList();
ViewData["ServiceID"] = new SelectList(a,serviceToUpdate.ServiceID);
In view:
#Html.DropDownListFor(model => model.ServiceID, ViewData["ServiceID"] as SelectList)
serviceToUpdate,ServiceID has the right value but somehow when I try to edit the selected value is not returned... instead the first value of dropdown is only returned...

I had the same problem. Use the null object pattern where you have a reserved id and the display name of the item is "please choose..." or something similar. Before passing in the model to the view, append to the beginning of the collection the null object. In the controller on the way back in, test for it. You can then set the property to null if the person didn't choose anything.
Here is my question:
DropDownListFor Not Displaying/Persisting Null for First Choice in List
You shouldn't have to use view data explicitly either like you are doing.

Code in Controller:
ViewBag.Services = new SelectList(a, "ServiceId", "#Servicename");
ServiceId is the property representing the key-value for the item displayed in the dropdown list
#Servicename stands for the property representing the text you want to display for the item in the dropdownlist)
Code in View:
#using(#BeginForm){
SelectList services = Viewbag.Services;
#Html.DropDownListFor(model => model.ServiceID, services)
}

Related

HTML Select control does not have selected value when generated with Razor DropDownListFor

I have a view in asp.net/mvc4/razor application where I want to edit value of model using dropdownlist control. I use it this way:
#Html.DropDownListFor(m => m.DateFormat, new SelectList(new [] {"mm/dd/yyyy", "dd/mm/yyyy"}))
The value of DateFormat property is set to one of those values in model but when I load the view, the html select is always set to first value. Am i missing sth?
UPDATE:
This was driving me nuts for two days. Finally I changed the name of property and it started to work. I think it somehow conflicted with value I stored in ViewData/ViewBag collection under the same key. I am not yet sure why. Maybe somebody can explain that?
Try your SelectList something like this where you define the text and the value, along with the selected item.
#(Html.DropDownListFor(m => m.DateFormat, new SelectList
(
new List<Object> {
new {
value = "mm/dd/yyyy", text = "mm/dd/yyyy"
},
new {
value = "dd/mm/yyyy", text = "dd/mm/yyyy"
}
}, "value", "text", Model.DateFormat)
))
This code is untested
Make the SelectList a buddy property of the model.
public class MyModel(){
prop DateTime MyDate {get;set;};
prop SelectList SelectDates {get;set;}
}
Then populate the SelectList after you have selected your date (remember to do this every time you build your model):
SelectDates = dates.Select(d => new SelectListItem
{
Value = d.ToString(),
Text = d.ToString(),
Selected = d == MyDate
})
Then use the property when you build your dropdown:
#Html.DropDownListFor(m => m.DateFormat, Model.SelectDates ))

replacing items in dropdownlist

I have a drop down list that is bound to some items. i want to replace the selected item with a text box value and again want to bind the dropdownlist with new values.
For this i am currently storing the dropdown list items in a temporary List. How can I replace the current selected item with textbox value.
for (int i = 0; i < DropDownEmail.Items.Count; i++)
{
if (?)
{
ObjRegistration = new ClassRegistration();
ObjRegistration.UserName = TextBoxEmail.Text;
tempEmailList.Add(ObjRegistration)
}
else{
ObjRegistration = new ClassRegistration();
ObjRegistration.UserName = DropDownEmail.Items[i].Text;
tempEmailList.Add(ObjRegistration);
}
}
Your code doesn't make much sense as it is written now, but in general, if you want to replace an item in a dropdown list you need to do something like this:
var selectedItem = tempEmailList.SelectedItem; //returns a ListItem object
selectedItem.Text=txtField.Text;
dropDownList.DataBind(); //Rebind it so you see the change.
In your case, it seems that you are binding to a custom collection of ClassRegistration but since you are doing this on code-behind, once you bind the elements to the Dropdown list for the first time, you only have a reference to the Items collection in the dropdown which are all of type ListItem.
You can, alternatively, update your underlying custom collection and rebind that to the dropdown list:
var tempEmailList= ... //get it from DB or whatever
tempEmailList.Find(x => x.ID == int.Parse(ddl.SelectedItem.Value)).UserName = txtBox.Text;
ddl.DataSource = tempEmailList;//re-assing the datasource
ddl.DataBind();//rebind

Using Html.DropDownListFor() with a SelectList

What is the correct way to populate a SelectList when using the Html.DropDownListFor helper in ASP.Net MVC 3?
I basically have a "Create" form which I want to specify the entry values on for a particular field. For example, it is a movie database and I want the ability to enter a Genre, but I don't want users to be able to enter what they like, so I assume a SelectList to be the best answer?
A way that works is to create a new class with a static method to return the SelectList:
public class Genres
{
public static List<string> GetGenres()
{
List<string> myGenres = new List<string>();
myGenres.Add("Comedy");
myGenres.Add("Romantic Comedy");
myGenres.Add("Sci-Fi");
myGenres.Add("Horror");
return myGenres;
}
}
Which can then be used like this:
<div class="editor-field">
#Html.DropDownListFor(model => model.Genre, new SelectList(OLL.Models.Genres.GetGenres()))
</div>
It just doesn't seem like the right/easiest way to do it? I think I'm missing something obvious here...
Thanks for any assistance you can provide.
This is a simple selectList style I use for drop downs all the time, hopefully you find this helpeful.
ViewBag.AlbumListDD = from c in db.Query<DatabaseEntities.VenuePhotoAlbum>("WHERE VenueId = #0", VenueId)
select new SelectListItem
{
Text = c.Name,
Value = c.Id.ToString()
};
Inside my view:
#Html.DropDownList("AlbumId", (IEnumerable<SelectListItem>)ViewBag.AlbumListDD, new { id = "ChangeAlbum" })
Hopefully you can find this useful as this is a database route to go. I typically like to have all of that sort of information in a database and that way users can dynamically add/remove and change these dropdown items at will. There is a bit of SQL work behind the scenes required when removing a type but it has proven to be very successful and fast for me at this point.
var og = (from s in DB.Products
select new SelectListItem
{
Text = s.ProductName,
Value = s.ProductID.ToString()
});
ViewBag.lstProducts = new SelectList(getproductname, "ProductID", "ProductName");
<p>
#Html.DropDownList("AlbumId", (IEnumerable<SelectListItem>)ViewBag.lstProducts, new { #id = "drp" });
</p>

enable html dropdown through controller in mvc

i have an scenario where i have to perform some action according to selection of the
dropdown .
for basic refrence you can use the example of country,state,city.
i am able to populate the country list at that time i have set the other two drop downs to
disable.
after the countries are populated i want to select the state.it is getting populated .
two problems
1) how to retain the state of country ddl as it is coming back to its orisnal state.
2) how to enable the drop down through my controller.
myview code
Country
<p>
<label>
State</label>
<%=Html.DropDownList("ddlState", ViewData["ddlState"] as SelectList, "--not selected--",new { onchange = "document.forms[0].submit()", disabled = "disabled" })%>
</p>
<p>
<label>
City</label>
<%=Html.DropDownList("ddlCities", ViewData["ddlCities"] as SelectList, "--not selected--", new { onchange = "document.forms[0].submit()", disabled = "disabled" })%>
</p>
my controller code
public ActionResult InsertData()
{
var customers = from c in objDetailEntity.Country
select new
{
c.Cid,
c.Cname
};
SelectList countriesList = new SelectList(customers.Take(100), "Cid", "Cname");
ViewData["ddlCountries"] = countriesList;
SelectList EmptyState = new SelectList(customers);
ViewData["ddlState"] = EmptyState;
ViewData["ddlCities"] = EmptyState;
Session["ddlSesCountry"] = countriesList;
return View();
}
//
// POST: /RegisTest/Create
[HttpPost]
public ActionResult InsertData(FormCollection collection)
{
try
{
CountryId = Convert.ToInt16(Request.Form["ddlCountries"]);
stateid = Convert.ToInt16(Request.Form["ddlState"]);
if (CountryId > 0 && stateid <= 0)
{
var stateslist = from c in objDetailEntity.State
where c.Country.Cid == CountryId
select new
{
c.Sid,
c.Sname
};
SelectList stateList = new SelectList(stateslist.Take(100), "Sid", "Sname");
ViewData["ddlState"] = stateList;
Session["StateList"] = stateList;
ViewData["ddlCities"] = stateList;
}
if (stateid > 0)
{
var citieslist = from c in objDetailEntity.City
where c.State.Sid == stateid
select new
{
c.Ctid,
c.Cityname
};
SelectList cityList = new SelectList(citieslist.Take(100), "Ctid", "Cityname");
ViewData["ddlCities"] = cityList;
ViewData["ddlState"] = Session["StateList"];
}
ViewData["ddlCountries"] = Session["ddlSesCountry"];
return View();
}
catch
{
return View();
}
}
My choice would be not to post back the form at all. I would write an action in the controller that takes a CountryID and returns a JsonResult holding a list of states. The onchange event could call a jQuery function that uses AJAX to call this action, loads the new list, and enables the second drop-down list.
However, if you stick with the postback, here's why it's not working:
The Country list isn't retaining its selected value because the view is being reloaded from scratch each time and you're setting it to "not selected." The SelectList constructor has an overload that takes a "SelectedItem" object as the fourth parameter. When you initialize your SelectList, you should pass the appropriate value to this parameter, and not force it in the View.
You need to write an "if" clause in your View to choose whether or not to enable the list based on some criteria. You could bind to a ViewModel that has a Boolean property like "EnableStates," or you could use something like the count of values in the StateList - if the count is greater than zero, enable it, for example.
A tricky thing to get used to when you move from Web Forms to MVC is that you don't have ViewState anymore - your application is stateless. There's nothing that "remembers" what value is selected in a drop-down for you, you have to set it each time you load the page.
I recommend using JSON & jQuery - like this posted answer.

MVC Drop Down List

This construction below using dropdownlist does not work!!
<% = Html.DropDownList (ddlUf, "All", New With (. Class = "text"})%>
It only works if I do this:
<% = Html.DropDownList (ddlUf, "All")%>
Or this:
<% = Html.DropDownList (ddlUf, Nothing, New With (. Class = "text"})%>
How do I solve this problem?
Thanks
use new{ #class = "text"})
I think you have the order of parameters mixed up. Assuming that ddlUf is a string with the DropDownList name, and "All" is supposed to be the default option, then you need something like this:
<% =Html.DropDownList(ddlUf, Model.FullListOfSelectListItems, "All", New With (. Class = "text") %>
There's some parameter order/validity issues here. The Html.DropDownList() method works by taking the following:
string name - assigns a name/id to the control
SelectList selectList - the list of options to appear in the drop down. You can construct this by creating a List and then using Linq to select the items from the list you want to appear in the drop down i.e:
List<string> myList = new List<string>();
//Add items to appear in the drop down.
myList.Add("Item1");
myList.Add("AnotherItem");
...
//Select all the items from the list and place them into a SelectList object.
SelectList dropDownList = new SelectList(from items in myList select items);
string optionLabel - the text for a default, empty item.
object htmlAttributes - a selection of HTML attributes to apply to the control.
So in your example you might want to go for something like:
#Html.DropDownList("MyDropDown", Model.MyConstructedSelectList, "Default item", new { #class = "text" })
For more information on using drop down lists with models in MVC, see this blog post:
http://277hz.co.uk/Blog/Show/10/drop-down-lists-in-mvc--asp-net-

Resources