C# - Convert List<Roomtype> To SelectList For ASP, MVC DropDownFor<>, And Get The Correct Values Per Option Item?
Jun 1, 2010
I have my class RoomType:
Int32 Id
String Name
String ColorCode
My viewmodel gets a List<Roomtype> RoomTypes which should be displayed in a dropdown.
Each dropdown option item should have: 1) as title the Name, 2) as value the Id, and 3) the style background-color #ColorCode.
My problems are how to convert this list correctly into a List<SelectListItem> as required by ASP.NET MVC's DropDownFor helper, and then to have the correct values inserted for each option.
I've tried to have a new readonly property in my viewmodel, which has a getter RoomtypeSelectList which returns new SelectList(RoomTypeList) but I can't get the correct properties to show (Name, Id, Background color).
I have a requirement in my application that, while saving the application, need to get all the value from drop down list and pass it to the view model. But application should not allow the user to select more than one item from drop down list manually, ie, only one value at a time. My view model is like ...
public class ListManagement { public IEnumerable<selectListItem> InactiveProduct { get; set; } public string[] InactiveProductSelected { get; set; } public IEnumerable<selectListItem> ActiveProduct { get; set; } }
I inherited an application written for VB.Net and am converting it over to ASP.Net, with VB as the back end. I have a data pull that adds values to a new instance of a class, then adds the item to a listbox. It worked great in the VB.Net version, but I get the following error in the Visual Studio Text Editor when I try to use the code:
Overload resolution failed because no accessible 'Add' can be called with these arguments:
'Public Sub Add(Item As System.Web.UI.WebControls.ListItem)':Value of type 'MyItem' cannot be converted to System.Web.UI.WebControls.ListItem'. 'Public Sub Add(Item as String)':Value of type 'MyItem' cannot be converted to String.
I have played around with the code quite a bit and have been researching online, but I'm just drawing a blank here.
I put the class("MyItem") in the "App_Code" folder in a file called "MyItem.vb". The class code is as follows:
[Code]....
The code I have for the sub that is supposed to add the items to the listbox is as follows:
What do I use to set the dataValueField of the Select List when I'm using a list of strings. I want to be able to set the value of the option in the select. If i have:
List<string> list = new List<string>(); list.Add("apple"); list.Add("orange");
I have a tabbed list that changes the div with javascript when selected. I would like to have have other pages on my site lead to and set a list item to active. With the code below my content_1 list item is set to active, I would like to have the active tab changed if say I selected a content_3 link from another page and I would like to set a custom url that will set content_3 to active when i go to the page with the list.
I have a dynamic dropdown that is populated from sql. The user is supposed to select an option from the dropdown, then click a search button on the form to return some results based on that selection. It works fine if the dropdown gets populated with more than one record. However, if only one record is returned, that one record can't be selected. Whether you select it or just leave it alone since it's the only one, when you click the form button (search button), no results are returned b/c the dropdown selection must not be actually selected.
I've included the relevant code below. First the DDL, then the datasource, and finally the C# code in the if (!Page.IsPostBack)
I am trying to create a simple page with a drop down list which has 3 items. Choosing any of those 3 items calls for a specific constructor in the script. Using VB 2008
public partial class _Default : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { } protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e) { if (DropDownList1.Text == "Coupe") { //Response.Write("You chose the Coupe"); string Engine; string Transmission; string Wheels; string Safety_Features; string Key_Systems; string Interior; string Mileage; Altima A1 = new Altima(Engine, Transmission, Wheels, Safety_Features, Key_Systems, Interior, Mileage); Response.Write(A1.displayAuto()); } if (DropDownList1.Text == "Hybrid") { Response.Write("You chose the Hybrid"); } if (DropDownList1.Text == "Sedan") { Response.Write("You chose the Sedan"); } } public class Altima { //private member variables private string Engine; private string Transmission; private string Wheels; private string Key_System; private string Safety_Features; private string Interior; private string Mileage; //public accessor methods public void displayAuto() { System.Console.WriteLine(Engine, Transmission, Wheels, Safety_Features,Key_System, Interior, Mileage); } //constructors public Altima(string Engine, string Transmission, string Wheels, string Safety_Features, string Key_System, string Interior, string Mileage) { this.Engine = Engine; this.Transmission = Transmission; this.Wheels = Wheels; this.Key_System = Key_System; this.Safety_Features = Safety_Features; this.Interior = Interior; this.Mileage = Mileage; string Engine = ("2.5-litre DOHC engine with 175 HP and 180 lb-ft of torque or 3.5-litre DOHC engine with 270 HP and 258 lb-ft of torque"); string Transmission = ("-speed manual transmission or available Xtronic CVT® with manual mode"); string Wheels = ("17 inch 5-spoke aluminum-alloy wheels (2.5 S) or 18 inch 5-split spoke aluminum-alloy wheels (3.5 SR)"); string Safety_Features = ("Six standard air bags as part of Nissan Advanced Airbag System (AABS)"); string Key_System = ("Nissan Intelligent Key® with Push Button Ignition"); string Interior = ("Leather"); string Mileage = ("Up to 5.6 L/100 km on city with eCVT"); }//coupe -------> First constructor public Altima(string Engine, string Transmission, string Safety_Features, string Mileage) { this.Engine = Engine; this.Transmission = Transmission; this.Safety_Features = Safety_Features; this.Mileage = Mileage; string Engine = ("2.5-litre DOHC engine with 175 HP and 180 lb-ft of torque or 3.5-litre DOHC engine with 270 HP and 258 lb-ft of torque"); string Transmission = ("-speed manual transmission or available Xtronic CVT® with manual mode"); string Safety_Features = ("Six standard air bags as part of Nissan Advanced Airbag System (AABS)"); string Mileage = ("Up to 5.6 L/100 km on city with eCVT"); }//sedan -----------> Second Constructor public Altima(string Engine, string Transmission, string Mileage) { this.Engine = Engine; this.Transmission = Transmission; this.Mileage = Mileage; string Engine = ("2.5-litre DOHC engine with 175 HP and 180 lb-ft of torque or 3.5-litre DOHC engine with 270 HP and 258 lb-ft of torque"); string Transmission = ("-speed manual transmission or available Xtronic CVT® with manual mode"); string Mileage = ("Up to 5.6 L/100 km on city with eCVT"); }//hybrid -----------> Third constructor } }
how do I ouput the values from the constructors when I choose the specific list box item?
So, I have 3 table adapters in my dataset, and trying to configure the objectDataSource will not give me the option to select the correct table adapter.
I set up a temporary website to illustrate what I am talking about, along with pics, not much, just 4 pics.
The first 2 pics are irrelevant but just in case anyone thinking I don't have it set up properly. The other table adapters are working fine, which I have gridviews being populated etc.
why it will not give me the option to select aspnet_GetRecordDatesTableAdapter?
I am stuck at this point "Displaying a dropdown list of Categories with a --None -- Option. I want the gridview control to display 2 dropdown list one in read-only mode and the other in edit mode. When a record is in read-only mode, the dropdownlist's enabled property will be set to false."When it's on a read-only mode, it doesn't display the selected Category. it shows but the "No Category". When i click on edit to edit or change category, it doesn't display the selected category.
The example is given below( I am reading the book Sams Teach yourself ASP.NET 2.0 by Scott Mitchell. page 628)
<asp:Label ID="UserIdValue" runat="server" Visible="False"></asp:Label> <asp:SqlDataSource ID="picturesDataSource" runat="server" ConnectionString="<%$ ConnectionStrings:ConnectionString %>" SelectCommand="SELECT * FROM [Pictures] WHERE ([UserId] = @UserId) ORDER BY [UploadedOn] DESC" DeleteCommand="DELETE FROM [Pictures] WHERE [PictureID] = @PictureID" InsertCommand="INSERT INTO [Pictures] ([UserId], [CategoryID], [Title], [Description], [UploadedOn]) VALUES (@UserId, @CategoryID, @Title, @Description, @UploadedOn)" UpdateCommand="UPDATE [Pictures] SET [UserId] = @UserId, [CategoryID] = @CategoryID, [Title] = @Title, [Description] = @Description, [UploadedOn] = @UploadedOn WHERE [PictureID] = @PictureID"> <DeleteParameters> <asp:Parameter Name="PictureID" Type="Int32" /> </DeleteParameters> <InsertParameters> <asp:Parameter Name="UserId" /> <asp:Parameter Name="CategoryID" Type="Int32" /> <asp:Parameter Name="Title" Type="String" /> <asp:Parameter Name="Description" Type="String" /> <asp:Parameter Name="UploadedOn" Type="DateTime" /> </InsertParameters> <SelectParameters> <asp:ControlParameter ControlID="UserIdValue" Name="UserId" PropertyName="Text"/> </SelectParameters> <UpdateParameters> <asp:Parameter Name="UserId"/> <asp:Parameter Name="CategoryID" Type="Int32" /> <asp:Parameter Name="Title" Type="String" /> <asp:Parameter Name="Description" Type="String" /> <asp:Parameter Name="UploadedOn" Type="DateTime" /> <asp:Parameter Name="PictureID" Type="Int32" /> </UpdateParameters> </asp:SqlDataSource> <br /> <asp:SqlDataSource ID="categoriesDataSource" runat="server" ConnectionString="<%$ ConnectionStrings:ConnectionString %>" SelectCommand="SELECT [CategoryID], [Name] FROM [Categories] WHERE ([UserId] = @UserId)"> <SelectParameters> <asp:ControlParameter ControlID="UserIdValue" Name="UserId" PropertyName="Text" /> </SelectParameters> </asp:SqlDataSource> <br /> <asp:SqlDataSource ID="maxPictureIDDataSource" runat="server" ConnectionString="<%$ ConnectionStrings:ConnectionString %>" SelectCommand="SELECT MAX(PictureID) FROM Pictures WHERE UserId = @UserId"> <SelectParameters> <asp:ControlParameter ControlID="UserIdValue" Name="UserId" PropertyName="Text" /> </SelectParameters> </asp:SqlDataSource> <br /> <asp:Label ID="cannotUploadImageMessage" runat="server" Text="The photo could not be added to your album either because you did not specify a file to upload or the file specified was not a JPEG image with the file extension .JPG"></asp:Label> <br /> <asp:DetailsView ID="dvPictureInsert" runat="server" DataSourceID="PicturesDataSource" Height="50px" Width="125px" AutoGenerateRows="False" CellPadding="4" DataKeyNames="PictureID" DefaultMode="Insert" ForeColor="#333333" GridLines="None"> <AlternatingRowStyle BackColor="White" /> <CommandRowStyle BackColor="#D1DDF1" Font-Bold="True" /> <EditRowStyle BackColor="#2461BF" /> <FieldHeaderStyle BackColor="#DEE8F5" Font-Bold="True" /> <Fields> <asp:TemplateField HeaderText="Picture"> <InsertItemTemplate> <asp:FileUpload ID="imageUpload" runat="server" /> <asp:RequiredFieldValidator ID="RequiredFieldValidator3" runat="server" ControlToValidate="imageUpload" Display="Dynamic" ErrorMessage="There was no file selected" ValidationGroup="PictureAdd"></asp:RequiredFieldValidator> </InsertItemTemplate> </asp:TemplateField> <asp:TemplateField HeaderText="Category" SortExpression="CategoryID"> <EditItemTemplate> <asp:TextBox ID="TextBox1" runat="server" Text='<%# Bind("CategoryID") %>'></asp:TextBox> </EditItemTemplate> <InsertItemTemplate> <asp:DropDownList ID="pictureCategory" DataSourceID="categoriesDataSource" runat="server" DataTextField="Name" DataValueField="CategoryID" SelectedValue='<%# Bind("CategoryID") %>' Visible='<%# Bind("CategoryID") %>' AppendDataBoundItems="True"> <asp:ListItem Selected="True" Value="">-- Select Category --</asp:ListItem> </asp:DropDownList> </InsertItemTemplate> <ItemTemplate> <asp:Label ID="Label1" runat="server" Text='<%# Bind("CategoryID") %>'></asp:Label> </ItemTemplate> </asp:TemplateField> <asp:TemplateField HeaderText="Title" SortExpression="Title"> <EditItemTemplate> <asp:TextBox ID="TextBox2" runat="server" Text='<%# Bind("Title") %>'></asp:TextBox> </EditItemTemplate> <InsertItemTemplate> <asp:TextBox ID="TextBox1" runat="server" Text='<%# Bind("Title") %>'></asp:TextBox> <asp:RequiredFieldValidator ID="RequiredFieldValidator1" runat="server" ControlToValidate="TextBox1" Display="Dynamic" ErrorMessage="you must provide a name for the title" ValidationGroup="PictureAdd"></asp:RequiredFieldValidator> </InsertItemTemplate> <ItemTemplate> <asp:Label ID="Label2" runat="server" Text='<%# Bind("Title") %>'></asp:Label> </ItemTemplate> </asp:TemplateField> <asp:TemplateField HeaderText="Description" SortExpression="Description"> <EditItemTemplate> <asp:TextBox ID="TextBox3" runat="server" Text='<%# Bind("Description") %>'></asp:TextBox> </EditItemTemplate> <InsertItemTemplate> <asp:TextBox ID="TextBox2" runat="server" Text='<%# Bind("Description") %>'
I have a list with 2 sorts of items. Items that have actual values (1,2,3,4 etc) and items that are like group headings so all their values are set to 0. If someone decides to select a group heading - which has a value of 0, is it possible to redirect them to my 'Select an item' item which has a value of ""?
If worse comes to worse, I can just reconstruct the entire list, although if possible I'd like to avoid it.
that I would like to be always, on page load, to mark the first option ("no expiration date"). However, if the user marks the second option and reloads, the second option is selected, even though I do this on page load:
I've been having issues with data downloaded using a .net WebClient control, in that I seem to have little control over the encoding of the data that I get back from a web server.
The specifics of the question are in the post linked below, but I want to ask the question in a more general sense as the answer is not really helping (not the answerer's fault!).
ASP.NET / C# WebClient.DownloadString() returns string with perculiar characters
The real problem is that supposedly there is no way to detect the encoding of a response from a web server, and the webserver may not respond using the encoding specified in the headers.
If this is true, how do web browsers such as IE, Firefox and Chrome work out how to decode the stream when you use the view source functionality?
when i click on the textbox which is inside the item template of gridview then onclick event should fire and then call the javascript function but my problem is that there no onclick event option in item template's textbox
How to set value to that? I want text to be displayed, and numeric value, to be inserted into database.Or maybe there is an option to handle that string text from my Action in Controller?
I have a drop down list control populated with items and some code to take the currently selected item value. The problem is I only get the value of the first item in the list regardless of what item is actually selected. Here is my code to populate the drop down:
protected void displayCreateCategories() { StoreDataContext db = new StoreDataContext(); var a = from c in db.Categories orderby c.Name select new{catName= c.Name, catId=c.CategoryID}; ddlCategory.DataSource = a; ddlCategory.DataTextField = "catName"; ddlCategory.DataValueField = "catId"; ddlCategory.DataBind(); }
To get the value of the currently selected item which in my case is always of type integer I do label1.text=Convert.toInt32(ddlCategory.SelectedValue); I get the selected value, but it is always for the 1st item in the list. I'm pulling my hair out over this.
Clicking the label of a drop down list, re-sets the selected value to the first item in the list. This has a history of causing data entry problems when users accidently click on the label.
In the below example ddlContactType has a selected value as 'PRIMARY' and whenever i click on the lblContactType Text, the dropdown box Selected value is changing to "Select One" Text.
How to prevent this one. It should be on PRIMARY Only.
I have a list of options (IEnumerable< SelectListItem >) in my model that I want to use in multiple dropdowns in my view. But each of these dropdowns could have a different selected option.
Is there an easy way to simply specfiy which should be selected if using the Html.DropDownList helper?
At this point, the only way I can see is to generate the html myself and loop through the list of options like so:
I have a master page which has an unordered list in this way:
[code]....
These links are directed to my content pages. I am able to highligt the selected list item on hover and on active.
But I do not understand how I can highlight the selected list item as long as the user is on that specific page/link (current list item). I know that we can specify a seperate body tag and id for each of the content pages and then use CSS to highlight the current list item, but all this code rests already inside a body tag in the master page.
I have a dropdownlist on my page that when a user selects an item sets the list for another dropdownlist. My problem is that no matter what the user selects in the 1st dropdown it resets itself to the first item in the list. I have autopostback=true and nableviewstate= true. Is there another setting i'm missing or is it my code?