.NET Tutorials, Forums, Interview Questions And Answers
Welcome :Guest
Sign In
Win Surprise Gifts!!!

Top 5 Contributors of the Month
Gaurav Pal
Post New Web Links

Beginner question: get selected value of Html.DropDownList

Posted By:      Posted Date: October 05, 2010    Points: 0   Category :ASP.Net

Hi everyone, how are you doing!

I'm just started learning MVC 2. I went through the music store example (though I don't 100% get everything). Now I want to add some functions to the page to learn more. I added paging, and now I want to add search combo boxes (drop down lists). Basically, in the album list screen, I want to add 1 drop down list of genre. If user select 1 genre then click Search, the page should show all album of that genre only.

My problem is I don't know how to get the selected value of this drop down list. The approach I am using now is to get the selected value, then put it as parameter and redirect to Index (/StoreManager/Index?searchGerneId=x). I searched through many posts but couldn't find a solution that works for me. It is probably because I don't really get MVC yet and still try to do things the code-behind way. So please help me :) My code  for Index in Controller is below

public ActionResult Index(int pageNumber = 1, int searchGenreId = -1)
            var albums = from album in storeDB.Albums
                         join genre in storeDB.Genres on album.GenreId equals genre.GenreId
                         join artist in storeDB.Artists on album.ArtistId equals artist.ArtistId
                         orderby album.Title
                         select al

View Complete Post

More Related Resource Links

Rendering data with HTML tags in the DD Gridview for a selected column


I am having trouble finding out where and how to HTML Encode a cell's data on the Dynamic Data (v4.0) gridview of List.aspx.  As a simple case, suppose I have formatted cell data that is A<br/>B in the DB.    Obviously, I want A stacked on B in the cell.

It seems gridView1.HtmlEncode = true has gone away.

So maybe I'll try to catch it on the RowDataBound event:

protected void GridView1_RowDataBound(Object sender, GridViewRowEventArgs e)

            if (e.Row.RowType == DataControlRowType.DataRow)
                // Html Encode the cells


but this event never fires?

Has anyone figured out how to properly render HTML tags data in the List.aspx's GridView1? 

If I figure this out, then I can add a MetaAttribute called something like [EncodeAsHtml(true)] and be on my way.  Thanks!

Conditional styles for selected Html.ActionLink


Hi, I am trying to add an item selected class to an Html.ActionLink, I am very new to MVC so its all a bit confusing.

So far i have each of my ActionLinks lookins like this

<li><%: Html.ActionLink("Home", "Index", "Home", new { @class = ViewData["current"] == "Home" ? "selected" : "" })%></li>

And in the controller i have

public ActionResult Index() {
            ViewData.Add("current", "Home");
            return View();

Can any one tell where i am going wrong because the links now fail to respond, basically it isn't checking the condition == Home and if it is then its failing because it doesn't get to the controller.

Any ideas would be appreciated


how can i display the selected value of dropdownlist from edittemplate to label from itemtemplate?


I have a detailsview with a dropdownlist in it. the detailsview is connected to a database table(employees having the following fields: id-smallint,name-nvarchar, departmnet-smallint). the ddl is connected to another table (departments with the following fields: id-smallint, departmentName-nvarchar). the ddl is in the edititemTempalte of the department field. My goal is to display in  the itemtemplate the departmentName (the selected value from the edititemtemplate ). How can I do this? Doyou have any ideas?

thanks a lot

Using AuthenticationService from pure html Question?

After searching the web I'm completely confused as to what my options are for using the AuthenticationService from a pure html page (with JavaScript, so NO asp.net webform and NO ScriptManager. I didn't found any clear code snippets for my problem. What I found where some 'pieces' of the puzzle.Option 1using an Authentication.svc file (see hereunder), adapting web.config and using javascript to use the Sys.Services.AuthenticationService methods. However by just using the Sys.Services.AuthenticationService.login method as-is (with the 8 parameters) the system gives a 500 error.Authentication.svc<%@ ServiceHost Language="C#"    Service="System.Web.ApplicationServices.AuthenticationService"    Factory="System.Web.ApplicationServices.ApplicationServicesHostFactory" %>Option 2Setting  Sys.Services.AuthenticationService.set_path("Authentication_JSON_AppService.axd"); and using the Sys.Services.AuthenticationService methods; here Sys.Services.AuthenticationService.login/logout works just fine.Can someone please explain me the differences of both approaches and where can i find clear examples of both approaches?Many thanks.

dropdownlist - default value is not 'selected value'

i have created a dropdown list that is populated from a sqlserver datasource. i have a separate sql command which uses the dropdownlist.selected value as a parameter and returns the command value to a label.  it mostly works fine but with one problem. when the page loads, the label value is null, because it doesn't seem to treat the dropdownlist default value as a selected value. when i use the dropdownlist to select a value, this is fine and the label begins to display the expected value. is there anyway I can make the default value when the page is loaded act like a manually selected value, so the label control never displays a null value?

I need a workflow triggered by a workflow...how do I design this? Beginner question

I've added the Approval workflow to a forms library and it generates the necessary tasks and emails for 2 levels (serial) of Approval on the form. When the form has been approved the 2nd time, I want it to trigger another workflow that notifies a 3rd person of the existence of the form and assigns her a separate non-approval task. I'm creating it in SharePoint Designer, and I can do most of it, but I'm not sure what field I'm looking for, at the beginning in order to start the workflow. Currently, there is no column for Approval Status in the form library, only a column that shows the status of the workflow (In Progress or Approved).  I tried If Workflow Status equals Approved then email.... but that didn't work. Any help is greatly appreciated.  I'm looking for the data source field and the list item field and value, I guess.  

ASP.Net MVC Dropdownlist and selected value problem

I was able to create a dropdownlist for my MVC project, but the value is not selected as  selected value on the dropdownlist. It just shows whole county list from the first.The value is from database. I tried find it from previous post, but it was quite confusing. Please, suggest me for any idea. Controller Code public ActionResult Edit(int i) {      var items = new SelectList(db.MST_COUNTRies.ToList(), "COUNTRY_ID", "COUNTRY_NM");      ViewData["MST_COUNTRies"] = items; } View Code <p>     <%= Html.DropDownList("COUNTRY_ID", (SelectList)ViewData["MST_COUNTRies"])%> </P>I was able to create a dropdownlist for my MVC project, but the value is not selected as  selected value on the dropdownlist. It just shows whole county list from the first.The value is from database. I tried find it from previous post, but it was quite confusing. Please, suggest me for any idea.Controller Codepublic ActionResult Edit(int i){     var items = new SelectList(db.MST_COUNTRies.ToList(), "COUNTRY_ID", "COUNTRY_NM");     ViewData["MST_COUNTRies"] = items;}View Code<p>    <%= Html.DropDownList("COUNTRY_ID", (SelectList)ViewData["MST_COUNTRies"])%></P>

Beginner question about eliminating Dups

I looked at a couple of links about eliminating dups. One  link suggested RowNUmber() function which is fine for 2005 (but I wanted something that would also work on 2000).  Another link was a MS article advising to select the dups into a temporary table. http://support.microsoft.com/kb/139444/en-us I found this article confusing, and I don't see why it suggests we need a holding table. So I propose this approach - is there any reason NOT to do it my way? (Is there a bug here I'm overlooking?) IF EXISTS(SELECT 1 FROM sys.tables WHERE NAME = 'Facilities' ) DROP Table dbo.Facilities; CREATE TABLE [dbo].[Facilities] ( [ID] int IDENTITY, [FacNo] varChar(3) , [theState] varchar(2) ) INSERT INTO Facilities ([FacNo], theState)VALUES ('1', 'FL') INSERT INTO Facilities ([FacNo], theState)VALUES ('7', 'FL') INSERT INTO Facilities ([FacNo], theState)VALUES ('25', 'FL') --- DUPLICATE THE FIRST THREE ROWS INSERT INTO Facilities ([FacNo], theState)VALUES ('1', 'FL') INSERT INTO Facilities ([FacNo], theState)VALUES ('7', 'FL') INSERT INTO Facilities ([FacNo], theState)VALUES ('25', 'FL') -- ADD some new rows. INSERT INTO Facilities ([FacNo], theState)VALUES ('4', 'VA' ) INSERT INTO Facilities ([FacNo], theState)VALUES ('5', 'VA' ) INSERT INTO Facilities ([FacNo], theState)VALUES ('10','Va') INSERT INTO

Fill a Listbox with value selected from a Dropdownlist

Hi, Maybe the question has already be posted, but I didn't find it.I have in my web page two controls: a dropdownlist and a listboxMy goal is to fill the listbox with values from my database depending on what I have selected in my dropdownlist.I wouldlike to use the CascadingDropDown component for that. Is that possible ??(I tried on my own and I get this error messageException Details: System.InvalidCastException: Unable to cast object of type 'System.Web.UI.WebControls.ListBox' to type 'System.Web.UI.WebControls.DropDownList'.I think it's when i tried to fill the listbox with this function:[WebMethod] public CascadingDropDownNameValue[] GetAppliForDomain(string knownCategoryValues, string category) { int domainID; //this stringdictionary contains has table with key value pair of country and countryID StringDictionary kv = CascadingDropDown.ParseKnownCategoryValuesString(knownCategoryValues); if (!kv.ContainsKey("Domain") || !Int32.TryParse(kv["Domain"], out domainID)) { throw new ArgumentException("Couldn't find Domain."); }; SqlConnection con = new SqlConnection(strConnection); SqlCommand cmd = new SqlCommand(); cmd.Connection = con; cmd.CommandType = System.Data.CommandType.Text

How to get item selected in dropdownlist

I'm searching and trying now for the last couple of hours, so I thought the community might help.I'm filtering the rows in a gridview using a ddlDate. Now, I want to request this selected item.But: When I load the page without clicking in the DropDownList, the ddlDate.SelectedValue is empty, and the ddlDate.SelectedItem.Text.ToString() gives a NullReferenceException.Is there any way to fix this without using a listbox?

Fetching DropDownList Selected Value

I'm having issues getting the selecteditems and value after Databinding a dropdown list.  I have a button event with dropdownlist2.Selecteditem.text, but will always get the "-- Select --" as the SelectedItem.text ?  Anybody know why this is happening ?   Dim conn As New SqlConnection '("xxxxxx") conn.ConnectionString = ConfigurationManager.ConnectionStrings("PostAdSqlServer").ToString Dim query As String = ("SELECT [CategoryId], [Name] FROM [Category]") Dim cmd As New SqlCommand(query, conn) cmd.Connection.Open() Dim ddlValues As SqlDataReader ddlValues = cmd.ExecuteReader() DropDownList2.DataSource = ddlValues DropDownList2.DataValueField = "CategoryId" DropDownList2.DataTextField = "Name" DropDownList2.DataBind() DropDownList2.Items.Insert(0, "-- Select --") cmd.Connection.Close() cmd.Connection.Dispose()    

dropdownlist selected item problum

In gridview we have edit button whenever user click edit button i want to show particular data of dropdownlist as a selected data that is selected by user as a selected text of dropdownlistis there any solution ???

Html.DropDownList using a List

This has to be a simple thing, but for whatever reason, I'm just not finding it. I want to use the HTML Helper function to create a DropDownList based on a List<string> (and actually have it bind to the data field on the model).  The simplest example, I suppose, would be: <%: Html.DropDownList("Material", new SelectList(new[] {"Wood","Brick","Metal"})) %> This creates the items in the drop-down, but of course, there's nothing in this line that would bind it to my model (model.Material).  I've done drop-downs with collections of models, where you can bind the Data and Display attributes to properties of the class, but I don't have a class here, just a List. Any ideas?

Selected Option from dropdownlist

 I need to figure out a way to modify the style property of a div on my page so that when a certain item ("Not shown - please quote") on a few different dropdownlists are selected,  the div style is set to "display: none". The dropdownlist gets generated dynamically and the amount of dropdownlists varys for each product. I've named the class via the cssclass property in the dropdownlist template usercontrol to be "dropDownClass".Here is my code for this page: <div id="ProductControls"> <div id="ProductOptions"> <div id="ctl00_MainContentHolder_VariantsDisplay_VariantsPanel" class="variantsdisplay"> <table> <tr class="dropdownlist"> <td class="choicelabel"><span id="ctl00_MainContentHolder_VariantsDisplay_modifierTemplate1_InputLabel">Color</span></td> <td class="choicefield"><select name="ctl00$MainContentHolder$VariantsDisplay$modifierTemplate1$ModifierList" onchange="javascript:setTimeout('__doPostBack(\'ctl00$MainContentHolder$VariantsDisplay$modifierTemplate1$ModifierList\',\'\')', 0)" id="ctl00_MainContentHolder_VariantsDisplay_modifierTemplate1_ModifierList" clas

How to Capture a DropDownList Selected Index Change Event

I have a gridview that receives data based on selection from a primary dropdownlist object. Works. Within the gridview, there is a dropdownlist whose selected index is based on the query from the primary dropdownlist. Works. Problem. How do I force the used to  change whatever value that the dropdownlist contains after they make their initial selection from the primary dropdownlist; except the default value of "Please make a selection". Gridview, contains a checkbox which drives whether a selected row is inserted into the data base. The databind in done using an ObjectDataSource on the presentation page, not in the code behind.   Thank you.   Ayomide 

dropdownlist selected value problem

i have dropdownlist<%= Html.DropDownListFor(model => model.SchoolDistrict,Model.sSchoolDistrict) %>To Poulate this value i have below code in controllerslist = new SelectList(list, "ID", "Name", selected);but what ever selected value i pass didnot shown in ddl

How to set selected value on asp:dropdownlist?

I am not a dev, I am sharepoint admin.  I have a SPD page with an asp:dropdownlist that uses a sqldatasource to populate the drop-down list.  This list does a postback which allows the user to select an item in the list and the rest of the page is generated based on the selection.  The user has options which include navigating away to another page with the id from the select passed as a query string to the new page.  This all works fine.  I am not using any bound fields or SSO for this because I need to execute a stored proc on the server to obtain the items populating the drop-down list. What I need to do now is allow the user to navigate back to the original page, however I want the original page to display using the same id passed in a query string rather than the default value of the datasource.  (so they don't have to select the same item from the drop-down list again after returning to the original page)  I can't seem to find a way to do this.  When I add a SelectedValue to the asp:DropDownList I get an error saying the Bind is not allowed.  I "thought" that I could add a querystring parameter to the datasource and use it as the selected value, but have not been successful.  I don't know if I am just doing it wrong or if this concept is wrong.  Below is the relevant code for the dro
ASP.NetWindows Application  .NET Framework  C#  VB.Net  ADO.Net  
Sql Server  SharePoint  Silverlight  Others  All   

Hall of Fame    Twitter   Terms of Service    Privacy Policy    Contact Us    Archives   Tell A Friend