How to display cascaded dropdownlist using MVC4?

I have two tables in DB to populate cascading dropdownlist. On change of value in first dropdown, second dropdown has to be populated
using second table. While i tried below code, i am getting the same data for country dropdownlist. countryid is primary key in country table and  it is
foreign key in state table. First row country id in state table is 6 which corresponds to North America in country table. It displays the same for all 11 rows in country dropdownlist. Please give me right direction?
  public ActionResult Submit()
           List<Country> allcountry= new List<Country>();
           List<State> allstate = new List<State>();
           using (portalconnectionstring pc = new portalconnectionstring())
                allcountry = pc.countries.OrderBy(a => a.countryname.ToList();
            ViewBag.CountryID = new SelectList(allcountry, "countryid", "countryname");
            ViewBag.StateID = new SelectList(allstate, "stateid", "statename");
             return View();
            [HttpPost]
            [ValidateAntiForgeryToken]
public ActionResult Submit(Feedback s) {
 List<Country> allcountry= new List<Country>();
 List<State> allstate= new List<State>();
 using (portalconnectionstring pc = new portalconnectionstring())
               allcountry= pc.countries.OrderBy(a => a.countryname).ToList();
               if (s != null && s.towerid > 0)
                    allstate= pc.states.Where(a => a.countryid.Equals(s.countryid)).OrderBy(a => a.statename).ToList();
 ViewBag.CountryID = new SelectList(allcountry, "countryid", "countryname", s.countryid);
          ViewBag.StateID = new SelectList(allstate, "stateid", "statename", s.stateid);
 if (ModelState.IsValid)
                    using (portalconnectionstring pc = new portalconnectionstring())
                        using (NpgsqlCommand pgsqlcommand = new NpgsqlCommand("ddltest", conn))
 pgsqlcommand.CommandType = CommandType.StoredProcedure;
 pgsqlcommand.Parameters.Add(new NpgsqlParameter("countryname", NpgsqlDbType.Varchar));
                        pgsqlcommand.Parameters.Add(new NpgsqlParameter("statename", NpgsqlDbType.Varchar));
  pgsqlcommand.Parameters[0].Value = model.countryname;
                        pgsqlcommand.Parameters[1].Value = model.statename;
 pgsqlcommand.ExecuteNonQuery();
                        ViewBag.Message = "Successfully submitted";
                else
                    ViewBag.Message = "Failed! Please try again";
                return View(s);
            [HttpGet]
            public JsonResult GetStates(string countryid = "")
                List<State> allstate= new List<State>();
                int ID = 0;
                if (int.TryParse(countryid, out ID))
                    using (portalconnectionstring dc = new portalconnectionstring())
                        allstate = dc.states.Where(a => a.countryid.Equals(ID)).OrderBy(a => a.statename).ToList();
                if (Request.IsAjaxRequest())
                    return new JsonResult
                        Data = allstate,
                        JsonRequestBehavior = JsonRequestBehavior.AllowGet
                else
                    return new JsonResult
                        Data = "Not valid request",
                        JsonRequestBehavior = JsonRequestBehavior.AllowGet
cshtml:
@model mvcdemo.Models.Feedback
    ViewBag.Title = "Submit";
<h2>Submit</h2>
@using (Html.BeginForm("Submit","cascadedddl",FormMethod.Post)) {
    @Html.ValidationSummary(true)
    @Html.AntiForgeryToken()
    <fieldset>
        <legend>Feedback</legend>
 <div class="editor-label">
            @Html.LabelFor(model => model.countryid)
        </div>
        <div class="editor-field">
             @Html.DropDownListFor(model => model.countryid,@ViewBag.CountryID as SelectList,"Select country")
            @Html.ValidationMessageFor(model => model.countryid)
        </div>
        <div class="editor-label">
            @Html.LabelFor(model => model.stateid)
        </div>
        <div class="editor-field">
            @Html.DropDownListFor(model => model.stateid, @ViewBag.StateID as SelectList, "Select state")
            @Html.ValidationMessageFor(model => model.stateid)
        </div>
 <p>
            <input type="submit" value="Create" />
        </p>
    </fieldset>
                <script type="javascript">
                    $(document).ready(function () {
                        $("#countryid").change(function () {
                            var countryID = parseInt($("#countryid").val());
                            if (!isNaN(countryID)) {
                                var ddstate = $("#stateid");
                                ddstate.empty(); 
                                ddstate.append($("<option></option").val("").html("Select State"));
                                $.ajax({
                                    url: "@Url.Action("GetState","cascadedddl")",
                                    type: "GET",
                                    data: { countryID: countryid },
                                    dataType: "json",
                                    success: function (data) {
                                        $.each(data, function (i, val) {
                                            ddstate.append(
                                                    $("<option></option>").val(val.stateid).html(val.statename)
                                    error: function () {
                                        alert("Error!");
                </script>

Please post questions related to ASP.NET in the ASP.NET forums (http://forums.asp.net ).

Similar Messages

  • How to display a pdf using outlook

    How to display a pdf using outlook

    You would normally right click on the PDF and select to open it with Acrobat. You have to have Acrobat or Reader installed on the machine.

  • How to display today date using formcalc

    Hi all,
    how to display today date using formcalc, eg April 20, 2009?
    Thanskks

    Num2Date(Date(), "DD/MMM/YYYY", "de_GB")

  • How to display HTML files using ABAP Webdynpro?

    Hi,
    I have a html index file and a bunch of other files accessed by the index file  in a specific directory on the SAP server. I'd like to display the index file via ABAP webdynpro and allow the users to click on what they need to see. How can I achieve this using utilizing the ABAP webdynpro technology ?
    Thanks!

    Hi Thomas,
    Thanks for taking the time to answer my question.
    I have the main html file and all other files needed by the main file in one directory on the application layer of SAP. I'd like to provide the user with a link, by clicking on which they should be able to get to the main html file using the browser. This is just a standalone application.
    I can try the approach using BSPs, however, I'm new to that area. Could you point me in the right direction to get started?

  • How to display dynamic images using Struts

    I am storing the image name in bean. I want to use the <html:img> tag to display my images. How can i do that using struts.
    Something or sort..
    <html:img src=bean:write name="pageEntry" property="pageImg"/>
    Thank You

    * In your web.xml file, add the struts-html-el.tld definition from the struts\contrib\struts-el\lib directory
    * Add this tag library to your JSP page; something like:
    <%@ taglib uri="WEB-INF/struts-html-el.tld" prefix="html-el" %>* Refer to the following example:
    <html-el:img src="${pageEntry.pagePic}" />* This assumes that pageEntry is a Bean, and pagePic is a bean variable accessed by the getPagePic() method.

  • How to display sample text using dynpage ?

    Hi All,
             I am developing the portal using dynpage technology.  I do not know whether I am posting this thread in the right place.
    How to display a sample text in the portal using dynpage?
    I have written it using HTMLFragment.  But it could not recognise the <> tags it seems.
    I am getting error in < and in \.  Can anyone pls help to resolve this?
    I tried with normal html tags.  It could not recognise the tags.
    Pls suggest.
    Regards,
    Subashini.
    Edited by: Subashini on Sep 16, 2008 7:48 AM

    Do read through this tutorial.
    http://help.sap.com/saphelp_nw70/helpdata/EN/95/cfa441cd47a209e10000000a155106/frameset.htm
    Thanks,
    GLM

  • How to Display Sub-Columns using ALV Grid

    Hi ,
      Could someone tell me how to display sub-columns under a parent column using ALV Grid. Do we have any standard Program which has this scenario. Please let me know.
    Thanks,
    Abaper.
    Message was edited by:
            ABAP'er

    you can check all with <b>BCALV* or RSDEMO*</b> in SE38 for all Std
    check below
    BCALV_DND_01                   Drag ALV Row to Tree Folder
    BCALV_DND_02                   Drag Icons from Tree to Rows of the Grid
    BCALV_GRID_DND_TREE            ALV Grid: Drag and Drop with ALV Tree
    BCALV_GRID_DND_TREE_SIMPLE     ALV GRID: Drag and drop with ALV tree (simple)
    BCALV_TEST_COLUMN_TREE         Program BCALV_TEST_COLUMN_TREE
    Rewards if useful............
    Minal

  • How to display Image by using Array?

    Hi all, I know to how to display the image in MXML by using
    AS 3.0
    like this:
    <?xml version="1.0"?>
    <mx:Application xmlns:mx="
    http://www.adobe.com/2006/mxml"
    width="100" height="80" borderStyle="solid">
    <mx:Script>
    <![CDATA[
    [Embed(source="logo.gif")]
    [Bindable]
    public var imgCls:Class;
    ]]>
    </mx:Script>
    <mx:Image source="{imgCls}"/>
    <!--OR-->
    <mx:Image source="@Embed('assets/Nokia_6630.png')"/>
    </mx:Application>
    But the thing is I am building a list for display the images,
    the values is come from the Array. I am trying a different way for
    display it but no working, here is my code:
    <?xml version="1.0" encoding="utf-8"?>
    <mx:Application xmlns:mx="
    http://www.adobe.com/2006/mxml">
    <mx:Script>
    <![CDATA[
    public var PICTURE_ARRAY:Array = [{label:"FileA",
    icon:"@Embed('upload/myjpg.jpg')"},
    {label:"FileC", icon:"@Embed('upload/myjpg.jpg')"},
    {label:"FileB", icon:"@Embed('upload/myjpg.jpg')"}]
    ]]>
    </mx:Script>
    <mx:Tile id="pictureSelection" height="180" width="500"
    borderStyle="solid">
    <mx:Repeater id="picRP"
    dataProvider="{PICTURE_ARRAY}">
    <mx:VBox horizontalAlign="center" verticalAlign="middle"
    verticalGap="0" borderStyle="none" width="100" height="100">
    <mx:Image width="80" height="80"
    source="{picRP.currentItem.icon}"
    toolTip="{picRP.currentItem.icon}"/>
    <!--
    I also tryed this as well:
    set the icon value as picture location like: "A.jpg" or
    "B.jpg"
    then
    <mx:Image width="80" height="80"
    source="@Embed('upload/{picRP.currentItem.icon}')" />
    -->
    <mx:Label text="{picRP.currentItem.label}" width="100"
    textAlign="center"/>
    </mx:VBox>
    </mx:Repeater>
    </mx:Tile>
    </mx:Application>
    Can anyone tell how to display the array value into Image
    tag? Thanks

    In your data you have this:
    {label:"FileC", icon:"@Embed('upload/myjpg.jpg')"},
    change it to this:
    {label:"FileC", icon:"upload/myjpg.jpg"}, // this is just the
    filename, not embedded
    In your Repeater you have this Image tag:
    <mx:Image width="80" height="80"
    source="{picRP.currentItem.icon}"
    toolTip="{picRP.currentItem.icon}"/>
    which is fine, except for the toolTip. The toolTip uses a
    string, not an image. If you want to show an image in the toolTip,
    you'll need to write your own toolTip class.
    Now the source property of the image will be given the URL to
    the image which will then be requested from the server and
    downloaded at runtime - it is not embedded.
    If you need to embed the images, then your dataProvider
    should have the variable name associated with the embedded
    image.

  • How to display addtocart button using Liquid

    I'm trying to output a custom layout of a product using Liquid, but can't figure out how to display the add to cart button as it's not included in the JSON. Liquid markup is all new to me so forgive me if I'm missing something obvious. Here is what I have for the layout but need an addtocart button.
    {module_product template="" collection="Classes" render="collection" catalogId="277528" productId="9231800"}
      <h1>{{Classes.title}}</h1>
       {{Classes.description}}
       <h3>Cost</h3>
       <p>{{Classes.saleprice}} + {{Classes.taxCode}} {{Classes.custom1}}</p>

    Ahh, Your rendering a product on just a page as a collection. May I ask why your trying to do that? Why are you not using the product eCommerce layouts.
    Doing what your doing you will only ever display information. You will never be able to do grouping, attributes or anything like that because they are more then just data output, they have functionality, BC script features and more to run off.
    Unless you 100% know how and you had all the info available (which you dont yet) to completely replicate every BC script feature etc - You will not be able to do what your doing.
    Liquid runs in layouts, just use product layouts and do things in there. I not seen on that page any reason why you would not be.

  • How to display an image using MIDP on Palm?

    How can I display an image using MIDP on Palm? The following code works on the Siemens SL45i, but not on Palm:
    public class Test extends List
    Image image = Image.createImage("/images/test.png");
    append("item 1", image);

    Have found the exact same problem when trying to display an image (other then the default (null)) in a list, on a Palm.
    The image displays correctly on a form, but when set on an element in the list, it does not display. (mind you this is in both emulator mode and on the real device)
    It does not seem to be related to size of the image.
    The Sun documetation states, that you should not rely on it been displayed (obviously it's an implementation issue with the Palm, and other devices I have not tried)
    But like to hear definitively from Sun though!

  • How to Display Sub-Columns using ALV

    Hi experts,
        Could someone tell me how to display sub-columns under a parent column using ALV. Do we have any standard Program which has this scenario. points are guaranteed for the right answer.
    Thanks in advance
    Sreenivas

    you can check all with <b>BCALV* or RSDEMO*</b> in SE38 for all Std
    check below
    BCALV_DND_01                   Drag ALV Row to Tree Folder
    BCALV_DND_02                   Drag Icons from Tree to Rows of the Grid
    BCALV_GRID_DND_TREE            ALV Grid: Drag and Drop with ALV Tree
    BCALV_GRID_DND_TREE_SIMPLE     ALV GRID: Drag and drop with ALV tree (simple)
    BCALV_TEST_COLUMN_TREE         Program BCALV_TEST_COLUMN_TREE
    Rewards if useful............
    Minal

  • How to display content without using webcenter services - task flows?

    Good day!
    I wanted to create a portlet where I can display and update an xml content retrieved from UCM Content Server. How can I do this without using taskflows (webcenter services)?
    Thanks in advance!
    Keith

    Hey Keith,
    Since you are already using the getResponseAsString() method you have your GET_FILE call working. To get the xml file as the file itself you need to instead call the getResponseStream() method. This will get you an InputStream representing the response.
    Once you have the stream you can do the following (I assume you are on a jsp page or somewhere you have access to the HttpServletResponse):
    String contentType = serviceResponse.getHeader("Content-Type");
    InputStream xmlInputStream = serviceResponse.getResponseStream();
    OutputStream outStream = response.getOutputStream();
    response.addHeader("Content-Disposition", "attachment;filename=myXmlFile.xml");
    response.setContentType(contentType);
    StreamUtil.copyStream(xmlInputStream,outStream,true,true);
    The runthrough:
    1. get the content type of the file coming back form the GET_FILE call
    2. grab the file as an InputStream
    3. get the output stream representing the response
    4. add a header to the response to trigger the "download file" dialog
    5. set the content type of the response
    6. copy the input stream to the output stream to send the xml file to the browser
    Notes:
    -StreamUtil is part of the RIDC jar
    -use Content-Disposition = inline to tell the browser to try and render the file in it's window if it can.
    Hope that helps,
    Andy Weaver - Senior Software Consultant
    Fishbowl Solutions < http://www.fishbowlsolutions.com?WT.mc_id=L_Oracle_Consulting_amw >

  • How to display mutilpe files using JFile choose

    please hepl me regarding how to select and display the mutilpe files using JFile chooser

    i m sorry if i have done any mistakes.i am new to
    this forum i just wanted to tell my problem and wish
    that it could ne solved...Tell it only once. Posting multiple times don't get more attention.

  • How to display "All Items" using a "Filtered Rows" Combo Box

    Hi
    How do I make a Combo Box with "Filtered Rows" show "All Values" by default, AND have the option to select individual filters?
    If my data was
    North
    South
    East
    West
    I would want the Combo box to display
    ALL
    North
    South
    East
    West
    When the user selected:
    North, they should see just the filtered rows with North
    South, they should see just the filtered rows with South
    ALL should be the default, and it should ifilter/include North, Soutn, East and West (i.e. showing all the rows)
    I need to use a Combo box and Filtered Rows, because I actually want to filter my dataset using multiple columns:
    Company, Region, District, Sector, Value
    My current method is to:
    use a Combo to filter the RawData on Company into an Intermediate_Company worksheet
    use another Combo to filter the Intermediate_Company worksheet on Region into an Intermediate_Region worksheet
    use another Combo to filter the Intermediate_Region worksheet on District into an Intermediate_District worksheet
    use another Combo to filter the Intermediate_District worksheet on Sector into an Intermediate_Sector worksheet
    then display in a List View from the Intermediate_Sector worksheet.
    Any comments on this method would also be welcome.
    Thanks for your help
    Stuart

    Thanks Muwa
    I've uploaded a non-working version here: http://www.teradepot.com/ntxgoo6629zi/Simple_All_Combo.xlf.html
    I've figured out how to use tthe filter to copy a subset of the rows in the source date to the destination are of the worksheet.
    I can't figure out how to use a filter to copy ALL the rows in the source to the destination.
    I've seen hints about using hidden filters, but I can't make this work, either.  It's quite depressing, really
    I'm very grateful for any help you can give.
    Thanks in advance
    Stuart

  • How to display large image using JAI

    dear all,
    could anyone tell me how do i display an image which is around
    5000x5000 pixels in JAI. I try to use BufferImage to store the image
    but JVM throws" out of memory " error while program is running.
    thanx a lot!

    just a rough estimate, but a 5000x5000 image would require at least 24MB assuming each byte is one pixal, I believe they are 4 bytes per pixel in RBGA format. (5000*5000) = 25,000,000 pixals /1024/1024 = 23.8MB for 1 byte pixals, *4 for 4 byte = 95.3MB. I'm pretty sure that this is how it stores it. Maybe I'm wrong but it certainly explains the situation. assuming you have at least 256MB ramm, run java with -Xmx200M and see what happens.
    java -Xmx200M app
    or if you have more ramm, like 512, use 450 or 500.

Maybe you are looking for

  • Firefox Display Discrepancy

    July 30, 2010 Hello: I have an existing site. http://envisioningmoore.com/ Last evening, I added two photographs to the collection.  The thumbnail and web size photos were added to the appropriate directories and they were added to the photo list (em

  • What is the latest version of Firefox that will work with Windows ME?

    We were recently given an older Gateway laptop that we intend to use solely as an internet terminal. Alas, it is running Windows ME and I don't even know if it has all the specs to upgrade (and certainly not to Vista, which is the only thing we have

  • IBooks has not been able to load or update for weeks. IPad2 Running 5.1.1

    iBooks has not been able to load or update for weeks...stuck. IPad2 Running 5.1.1

  • Lumia 730 review

    Hi there,           Its been 15days i have used my lumia 730. I had found some minor issues that can been resolved. Lumia 730 rocks.... 1. Amazing camera quality (front and rear). 2. After installing 86apps (76 in my SD card) in my lumia 730, it just

  • IPTC Daten werden nach upload in bildagentur nicht dargestellt?

    Hi! Ich habe bis dato mein pics problemlos verschlagwortet und bei bildagenturen per FTP hochgeladen. Alles war da. titel, objekt, mein name, stichworte. Nun bin ich auf phtoshop Ce3 mit bridge adobe c3 umgestiegen, habe gestern alles brav verschlagw