Based on selected value from HTML.Dropdownlist, the values to be fetched

Hi, 

 I'm using Html.DropDownList.  When selection within this box changes, I need to retrieve the values from table based on the selected id(datavaluefield) of dropdownlist.

Here my code

 

ViewPost.cs viewpage

 
<%=Html.DropDownList("CategoryID",ViewData["CategoryID"])%>  ---- based on selected value from the user the below table should fetch the value the db

 <table>
        <tr>
          
            <% foreach (VMLBlogsite.Models.Tbl_PostExperience post in (IEnumerable<Tbl_PostExperience>)ViewData.Model)
     {%>
            <tr>
                <td> Title </td>
                <td>
                    <%=post.Title %>
                </td>
                 <td>
                    <%=post.Ctg_Id %>
                </td>
               
                <td>PostComments
               
                <%= Html.ActionLink("PostComment", "PostComment", new { id = post.PostId })%>
     
               </td>
               
                </tr>
                <tr>
                <td> Description</td>
                <td colspan=2>
                    <%=post.Description %>
                </td>
               </tr>
            <% }%>
        </tr>
    </table>
  

 
Controller

   public ActionResult ViewPost()
        {
            New();      
         } 

 

 public ActionResult New()
        {

           var categories = from c in db.Tbl_BlogCategories select c;
            ViewData["CategoryID"] = new SelectList(categories, "Ctg_Id", "Ctg_Name");
            return View();
     }

0
Ambikaa
10/23/2008 1:01:52 PM
asp.net.mvc 4300 articles. 0 followers. Follow

2 Replies
1469 Views

Similar Articles

[PageSpeed] 51

You can solve this in two ways - you can re-render whole page or some part of page only (using AJAX). In both solutions you must use onchange event of select HTML element to handle when user changes selection.


Don't forget to click "Mark as Answer" on the post that helped you.
0
Augi
10/24/2008 1:02:23 PM

 Well, I am completely new in ASP.NET MVC, so... probably it's not a goooood solution. But, it works and can give you insights on better way to do it. I don't know it it is exactly what you need, but it lists the products of a category specified on a dropdownlist.

 

	// ====================
// Controller Code
// ====================


[AcceptVerbs(HttpVerbs.Get)]
public ActionResult ListByCategory()
{
IEnumerable<categories> = this.CategoryRepository.All();
IEnumerable<products>;

ViewData["Categories"] = categories;
if (categories.ToList().Count > 0)
{
ViewData["CategoryID"] = categories.First().ID; // To hold the value on the dropdownlist
products = this.ProductRepository.FindAll(x => x.CategoryID == (int)ViewData["CategoryID"]);
}
else
{
ViewData["CategoryID"] = 0;
produtos = this.ProductRepository.All();
}

return View(products.ToList());
}


[AcceptVerbs(HttpVerbs.Post)]
public ActionResult ListByCategory([Bind(Include="CategoryID", Prefix="Product")] Product p)
{
ViewData["Categories"] = this.CategoryRepository.All();
ViewData["CategoryID"] = p.CategoryID;
var products = this.ProductRepository.FindAll(x => x.CategoryID == p.CategoryID);
return View(products.ToList());
}

  // ====================
  // View Code
  // ====================

    <%  using (Html.BeginForm())
       { %>
            <%= Html.DropDownList(null,"Product.CategoryID",
                                   new SelectList((IEnumerable<Category>)ViewData["Categories"], "ID", "Description", (int)ViewData["CategoryID"]),
                                   new { onchange = "document.forms[0].submit()" }
                                  ) %>
                                 
                                 
    <%  } %>
         
    <ul>
    <% foreach (var product in ViewData.Model)
       {  %>
            <li>
                <h3><%= product.Title %></h3>
                <p><%= produto.Description %></p>
                <p><%= produto.Price %></p>
            </li>
           
    <% } %>
    </ul>
0
nepomucenobr
10/24/2008 8:02:21 PM
Reply:

Similar Artilces:

DropDownList value selected base on database value?
Hi, is there anyway how I can allow my dropdownlist (on pageload event) to select the value base on the value found in the database, in addition I also want the dropdownlist to contain other values too however the selectedValue must be the one found in the database. Sorry if it sounds confusing. I'm using VB.NET 2003 with ASP.NET Thanks. Hi,Whatever you want to get selected for your dropdown use following code.if(dropdownid.items.findbyvalue("value") != null){    dropdownid.items.selecteditem = false;    dropdownid.items.findbyvalue("value").selected = t...

Dropdownlist selected value passes first value in list no matter what value is selected. why ?
 HI . I have a dropdownlist. Databinds ok but when I must pass a value as a Selected value it always passes the first value in the list even if I select another value. I tried to set the ddl to enableviewstate false but it doesn't change anything. Any ideas ? Code below, thanksLoading the ddl:       productCategories = CatalogAdmin.Admin_Product_Categories_NotIn(productId);        for (int i = 0; i < productCategories.Rows.Count; i++)        {       &...

Fetch the value into text box based on the value selected
I have a DataGrid in which it has two DropDowns and two TextBox.one DropDown Have Months like Jan,Feb..... Another is Populated with Years.Based on the month and year selected the TextBoxes have to to be filled with the month Startdate (If is Jan-1/1/YY) and Enddate(1/31/YY).If the month is Feb it has to get only 28 days as Enddate,If it is leap year it has to be filled with MM/29/YY.  Please help, ravi.   There are two options for you, either define a function, that calculates the number of days in that mo...

How Select one dropdownlist value using down arrows corresponding other dropdownlist value are select
I am using two dropdownlist box.One is used for country selection. other one is used for state selection.I am using dropdown selectedindexchanged event. when i click country dropdownlist corresponding state is selected in state dropdownlist box. How select the country in country dropdownlist using down arrow keys at the same time corresponding state is select in state dropdown list.R.Karthikeyan   kartmca: How select the country in country dropdownlist using down arrow keys at the same time corresponding state is select in state dropdown list.Generally, we don't implmenet...

VB.NET
I have a DataGrid (see code at end of my question) with several dropdownlist controls within TemplateColumns for Editing.  For the first 2 ddls in my grid, ddlMedType and ddlMedicationName, I would like to populate ddlMedicationName based on the selecteditem of ddlMedType, but I don't know how to reference this. Thank you for saving me from confusion!!!! Here is my DataGrid code: NOTE: I've bolded the 2 controls that I need help with -- the rest you can really ignore!! ================== <asp:datagrid id="dgMeds" runat="server" OnEditCommand="dgMeds_EditRow" OnUpdateComm...

DropDownList selected value determines value of second DropDownList
I have a quick question that I'm sure has been addressed before, but I can't seem to find a solution. I have two drop down list fields: startTime and endTime coded as such: <asp:DropDownList id="startTime" runat="server"> <asp:ListItem Value="00:00">12:00 A.M.</asp:ListItem> <asp:ListItem Value="00:30">12:30 A.M.</asp:ListItem> <asp:ListItem Value="01:00">1:00 A.M.</asp:ListItem> <asp:ListItem Value="...

Change Another Column Value based on Dropdownlist selected value while gridview onrowediting
Hi everyone. Another gridview question again. I have a gridview, with three columns, Code, Description and Action. The Code column, when I click on the Edit linkbutton on the Action column becomes a dropdown list. How can I do that when I selected a value from the dropdownlist, the value of the description on would be changed to the description corresponding to the dropdownlist? Thanks.   Hi:   From your description I think you can try: 1. Set AutoPostBack=true for your DropDownList. 2. protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e) &n...

Selected value in select list with javascript based off value in database
 I've got a classic asp page with a select list. I need the select list's selected value to be whatever the user selected when they created their account. I've been trying to use <body onLoad="onLoad();"> to call my function, and then I'm trying to specify which value should be selected in the function. Also, when the select list selected values change, there is a javascript function I call to disable text boxes. I think there is an issue with my javascript function, and I can't find any examples of this from good ole' google.  My j...

dropdownlist's selected index value is not printing the selected value
Here iS my code .Aspx Page <asp:DropDownList ID="ddlkeyword" runat="server" Width="204px" DataTextField="Form" DataValueField="Form" OnSelectedIndexChanged="ddlkeyword_SelectedIndexChanged" >   </asp:DropDownList> <asp:Button ID="Button1" runat="server" Text="Submit" Width="110px" OnClick="Button1_Click" /> my aspx.cs protected void Page_Load(object sender, EventArgs e) { fillddlkeyword(); }protected void Page_Init(object sender, EventArgs e) { ...

Form: Focus on selected values in dropdownlists, Refresh after selection and hidding formfields based on selection.
Hello again,I have a form with several dropdown lists. Depending on the selected value in the dropdown lists other fields become available in that same form. It is working in classic ASP in combination of JavaScript. I want to migrate it to ASP.NET. I have posted a part of the form at the end of this post.My questions:1. I use <option <%If iFood="0" then%>selected<%End If%> value="0">No value selected</OPTION> to select the selected item when the form is reloaded after the selecting. I know that this also works in ASP.NET, but isn't there a typical ASP....

HTML.select (UI helper) how to build a select list with value not equal to the display value
Hi Guys, I have a newbie question on HTML.select (UI helper). One of the tutorial I have come across shows the following: "string [] SelectList = new string[]{'Apple', 'Orange','Mango','Banana'};" "Html.Select('FruitList',SelectList)" it will give me:value = "Apple"  "Apple " However, I would like to have the following instead: value = "1"  "Apple " What should I do on the VIEW in order to achieve this? thx, George what you need to do is create a collection to use for your data sou...

Setting a dropdownlist value based on a value in a Database
I have a page that allows users to create a user account. The aspx has various dropdowns that I populate by binding the dropdownlist to a dataset. OK so far? However, I also want a page where the user can edit their profile..so I need to be able to set the selected value based on what is saved in my user table and I also need to add the extra entries. Anyone know how I can do this easily. Do I need to join on my user table and my table that has all the various categories in order to get the selected value and add my other values?? Thanks, COG. For selecting the correct...

Setting a label value to a dropdownlist selected value
I am trying to set the value of a label to the selected value from a hidden dropdown list. This code is not working and the label value remians at its default. Any ideas? Thanks very much. Protected Sub DetailsView1_DataBound(ByVal sender As Object, ByVal e As System.EventArgs) Dim mylabel As Label Dim myddl As DropDownList If (DetailsView1.CurrentMode = DetailsViewMode.ReadOnly) Then mylabel = DetailsView1.FindControl("Label1") myddl = DetailsView1.FindControl("DropDownListViewOffice") mylabel.Text = myddl.SelectedValue.ToString End If I have now put this code in the Page_Load su...

Handling DBNull Values in DropDownList Selected Value
I have a dropdown list inside a formview that is used to update a business opportunities table. Each opportunity may or may not have a salesperson assigned. On the update page I want to set the current value in the database as the selected value in the dropdown list. But if there is no salesperson assigned i need to handle the dbnull value and not try to set the selected value. Can someone give me some pointers? Should i handle this in the Formview_databinding event or in the Datasource for the opportunity Databinding event? How do i get at the cell of the datasource that i need to test for ...

Web resources about - Based on selected value from HTML.Dropdownlist, the values to be fetched - asp.net.mvc

Tag Synonyms - Stack Overflow
Q&A for professional and enthusiast programmers

Accidental entities - what about the UI?
This post is a follow-up to my previous blog post " Accidental entities - you don't need that identity ". In that post, we followed a consultant ...

Flash Builder Plug-in for SAP Netweaver Gateway - Adobe Labs
Search Navigation Labs Home Wiki Home Technologies Alchemy Blueprint Camera Profiles and DNG Profile Editor Cirrus ColdFusion 10 DNG Codec Fireworks ...

Air Astana - Join Now
Thank you for considering membership of Nomad Club – Kazakhstan’s first Frequent Flyer Program. You could soon be on your way to earning free ...

Languages -> C# Articles, Tutorials, Examples: ASP Alliance
.NET,ASP,ASP.NET,SQL,XML,HTML,ADO,ADO.NET,JavaScript,JScript,CSharp,VBScript and VB tutorials from AspAlliance.

Blog - Avisra
Avisra Web Development Home Blog Services Contact The Blog Latest Module Builder: How can we make it better? Sitefinity by Chris on July 2, 2013 ...

Online Booking Tool Support
This Online Booking Tool Support page might help you as you navigate through the process of booking travel through your OBT provided by CWT. ...

@Html and beyond
... ); } return string .Format( “{0}{1}” , me.Member.Name, id); } The Html building methods are quite simple. Building a dropdownlist for a ...

Top Ranked Articles
Top Ranked Articles - Free source code and tutorials for Software developers and Architects.; Updated: 23 Feb 2013

Unit Testing DateTime.Now Without Isolation
public virtual void SeedWithYearsSince(DropDownList list, int year){ for (int index = year; index

Resources last updated: 12/7/2015 10:54:33 AM