Rectangle 27 1

The Tip you are using: ASP.NET MVC Tip #41 Create Cascading Dropdown Lists with Ajax from Stephen Walther was not done with MVC Realease 1.0

As such, it works fine with the downloaded project (after fixing some small issues), but when the you try to incorporate into MVC Release 1.0 things break.

For example: in the downloaded project, the scripts are in the Content Folder, in Release 1.0, the scripts are in the Scripts folder.

Also some (if not all) of the *.js files in the release changed from the bets and CTPs. This may be a problem too.

I downloaded his project (fixed a couple of minor issues), and it worked fine within that project (the *.js files).

So as you see, there are some issues.

These type problems with tutorials and blogs are abundant; everyone wants to be considered an "Expert" on new technology being released so they write tutorials on betas and CTPs. The result is that the "Expert" will have stuff that doesn't work with the final release.

What you need to find is a Professional that has posted tutorials. A Professional will ensure that their tutorials work. What I mean by a professional is a professional trainer in that area of technology.

Stephen Walther has one of the better blogs and a lot of good stuff, but remember that he is a Microsoift Evangelist. He authors books on MS technology so he needs to be active in the blog world so he puts some good stuff out on leading edge technology. This keeps him deemed as an expert so his books can sell.

Just remember, regardless of the "Expert", there will be inaccuracies in blogs/writings (based on betas and CTPs) when you try to use the information in a final release.

cascadingdropdown - ASP.NET MVC - Cascading Drop Down - Stack Overflow

asp.net-mvc cascadingdropdown
Rectangle 27 1

The Tip you are using: ASP.NET MVC Tip #41 Create Cascading Dropdown Lists with Ajax from Stephen Walther was not done with MVC Realease 1.0

As such, it works fine with the downloaded project (after fixing some small issues), but when the you try to incorporate into MVC Release 1.0 things break.

For example: in the downloaded project, the scripts are in the Content Folder, in Release 1.0, the scripts are in the Scripts folder.

Also some (if not all) of the *.js files in the release changed from the bets and CTPs. This may be a problem too.

I downloaded his project (fixed a couple of minor issues), and it worked fine within that project (the *.js files).

So as you see, there are some issues.

These type problems with tutorials and blogs are abundant; everyone wants to be considered an "Expert" on new technology being released so they write tutorials on betas and CTPs. The result is that the "Expert" will have stuff that doesn't work with the final release.

What you need to find is a Professional that has posted tutorials. A Professional will ensure that their tutorials work. What I mean by a professional is a professional trainer in that area of technology.

Stephen Walther has one of the better blogs and a lot of good stuff, but remember that he is a Microsoift Evangelist. He authors books on MS technology so he needs to be active in the blog world so he puts some good stuff out on leading edge technology. This keeps him deemed as an expert so his books can sell.

Just remember, regardless of the "Expert", there will be inaccuracies in blogs/writings (based on betas and CTPs) when you try to use the information in a final release.

cascadingdropdown - ASP.NET MVC - Cascading Drop Down - Stack Overflow

asp.net-mvc cascadingdropdown
Rectangle 27 1

Your script is before the the element with id="SelectedDistrict" and not wrapped in $(document).ready() so your attaching an event to an element which does not even exist at that point.

Move the script to the bottom of the page (immediately before the closing </body? tag and/or wrap it inside document.ready

$(document).ready(function() { // or $(function() {
    $('#SelectedDistrict').on('change', function () {
        ....
    });
});

Side note: Update your version of jquery to a recent version and consider returning json to populate your 2nd dropdown (refer this answer)

I've tried wrapping in the document.ready & have tried suggestions in the post you linked. None of these have changed what the program does as far as I can see. I have placed some breakpoints and it seems as if the code doesn't make it into the script. I think my SchoolDistrictInformation controller might have something to do with it. My school table is already populated with all the names from the School table.

I changed my version from 3.0.2 to 1.10.2 and it goes into the script now. everything else that I have mentioned is still a problem.

Which problem are you referring to. You have now modified you script to add options based on the return data being json, but the GetSchools() method returns html (a partial view) so of course it wont work. In any case you have decorated it with [HttpPost] (despite it being a GET method) but $.getJSON() call a GET method (hence its name). If you going to use the code in the links, then study it and do it correctly.

Oh man, I missed the [HttpPost] since it's so easy to scroll by. I changed the return partial to a return json when I changed the JSON method I just forgot to update it, sorry about that. Where I am currently is that the value of the selection I make from the first dropbox is not being saved to the view model / passed to GetSchools(). So when I use model.SelectedDistrict to query the database, it's value is null. Because of this, the 2nd dropbox changes to having one selection with the text "Please Select" since that's what is in the text value in the script.

I have rolled back you edit to the original because that is what my answer was based on. You cant completely change the question making everyone answer completely useless. Your original code did not work for the reasons in my answer (the script never fires because it's not inside $(document).ready()

mysql - Cascading Drop Down List in MVC w/ SQL Database - Stack Overfl...

mysql ajax asp.net-mvc cascadingdropdown
Rectangle 27 1

The reason your second <select> element does not submit a value is because it does not have a name attribute. It would need to be

<select class="form-control" name="TourDate.TourId" id="TourId"></select>

However there are multiple other errors and problems with your code. To note just a couple of them:

  • The model in your view is is not typeof TourDate (its a model containing a property which is TourDate) so none of your controls can be bound to your TourDate tourDate parameter in the POST method (the model in the parameter needs to be the same as the model in the view, or you need to use the [Bind(Prefix = "TourDate")] attribute and you also need to remove the [Bind(Include = "..")] attribute).
  • Your not getting client side validation associated with your dropdownlists and in the POST method, if ModelState is invalid, your just redirecting (the user would just assume the object has been saved and not understand what is going on). You need to return the view so errors can be corrected, but in your case, the values the user has entered will be reset to the defaults (an annoying user experience).

Your editing data, so you should always use a view model and in the controller method you need to populate the SelectList's to account for initial values and edited values (for when you need to return the view). You code should be

public class TourDateVM
{
    [Required(ErrorMessage = "Please select a country")]
    [Display(Name = "Country")]
    public int? SelectedCountry { get; set; }
    [Required(ErrorMessage = "Please select a tour")]
    [Display(Name = "Country")]
    public int? SelectedTour { get; set; }
    [Required(ErrorMessage = "Please enter a start date")]
    [Display(Name = "Start date")]
    public DateTime? StartDate { get; set; }
    .... // ditto above for EndDate
    public IEnumerable<SelectListItem> CountryList { get; set; }
    public IEnumerable<SelectListItem> TourList { get; set; }
}

And in the controller

public ActionResult Create()
{
    TourDateVM model = new TourDateVM();
    ConfigureViewModel(model);
    return View(model);
}
[HttpPost]
public ActionResult Create(TourDateVM model)
{
    if (!ModelState.IsValid)
    {
        ConfigureViewModel(model);
        return View(model);
    }
    TourDate tour = new TourDate()
    {
        TourId = model.SelectedTour,
        StartDate = model.StartDate,
        EndDate= model.EndDate
    };
    db.TourDates.Add(tour);
    db.SaveChanges();
    return RedirectToAction("Index", "Home");
}
private ConfigureViewModel(TourDateVM model)
{
    var counties = db.Countries;
    model.CountryList = new SelectList(counties, "ID", "Name"); // adjust to suit your property names
    if (model.SelectedCountry.HasValue)
    {
        var tours = db.Tours.Where(e => e.CountryId == model.SelectedCountry);
        model.TourList = new SelectList(tours, "Id", "TourName");
    }
    else
    {
        model.TourList = new SelectList(Enumerable.Empty<SelectListItem>());
    }
}

and finally in the view (note that both dropdownlists need to be inside the <form> element)

@model TourDateVM
....
@using Html.BeginForm())
{
    ....
    <div class="form-group">
        @Html.LabelFor(m => m.SelectedCountry, new { @class = "control-label col-md-2" })
        <div class="col-md-10">
            @Html.DropDownListFor(m => m.SelectedCountry, Model.CountryList, "- Please select -", new { @class = "form-control" })
            @Html.ValidationMessageFor(m => m.SelectedCountry, "", new { @class = "text-danger" })
        </div>
    </div>
    <div class="form-group">
        @Html.LabelFor(m => m.SelectedTour, new { @class = "control-label col-md-2" })
        <div class="col-md-10">
            @Html.DropDownListFor(m => m.SelectedTour, Model.TourList, "- Please select -", new { @class = "form-control" })
            @Html.ValidationMessageFor(m => m.SelectedTour, "", new { @class = "text-danger" })
        </div>
    </div>
    ....
}

and the script should be

var url = '@Url.Action("GetT")'; // assumes its in the same controller
var tours = $('#SelectedTour');

$('#SelectedCountry').change(function() {
    tours.empty();
    $.post(url , { id: $(this).val() }, function(data) {
        if (!data) {
            return;
        }
        tours.append($('<option></option>').val('').text('- Please select -'));
        $.each(data, function(index, item) {
            tours.append($('<option></option>').val(item.Id).text(item.TourName));
        });
    });
})

Excuse me I know I shouldn't continue on this. my problem solved completely but I had to change it a little. as initializing has an Error I did something like this . before sending my model to configureviewmodel initialize it like this model.StartDate = Convert.ToDateTime("2015-03-25"); model.EndDate = Convert.ToDateTime("2015-03-25"); first I need to know if its correct way? and then I have some problem in its format which saved in database

Why are you needing to use Convert.ToDateTime()? You should not need to do that (the properties should already be typeof DateTime)

Sorry, still not clear what the issue is. When you first pass the model to the view and you want to set some defaults, then initialize a new instance of the view model and then model.StartDate = DateTime.Today; (for today's date) or model.StartDate = new DateTime(2015, 3, 15); for a specific date. Or you could that in a parameterless constructor for the view model.

The reason for using DateTime? in a view model with a [Required] attribute is to protect against under-posting attacks.

ajax - how to save items of cascading drop down list in database with ...

ajax asp.net-mvc cascadingdropdown
Rectangle 27 2

The correct way is to only have one form. Then use AJAX to populate the cascading drop down list. The are 100s of examples online how to do this with JSON

How to handle nested forms in ASP.NET MVC - Stack Overflow

asp.net-mvc-3
Rectangle 27 1

What you are looking for is building a cascading drop down list. You will need to either implement something to load data via ajax as a drop down is selected or you will need to do a postback (not recommended).

c# - ASP.NET MVC 5 querying database with 3 DropDownList - Stack Overf...

c# asp.net asp.net-mvc asp.net-mvc-4 asp.net-mvc-5
Rectangle 27 1

The idea of cascading dropdown is, When you load the page, you load the dropdown content for the first SELECT element. The second SELECT element will be an empty one. When user selects an option from the first dropdown, send that to the server which returns the content needed to build the second dropdown.

So in the GET action of your page, get the data needed to render the first dropdown.

public ActionResult Welcome()
{
  ViewBag.Companies = new SelectList(db.Companies, "CompanyID", "CompanyName");
  return View();
}

Now in the view, you can use the DropDownList helper method to render the SELECT element with the data we set to the ViewBag.Companies. We will also add our second dropdown as well.

@Html.DropDownList("Company", ViewBag.Companies as SelectList)
<select name="id" id="vacancy" data-url="@Url.Action("Vacancies","Home")">

Now we will use some ajax code(using jQuery in this example) to get the content for the second dropdown. Register an event handler for the change event of the first dropdown, get the selected value, make an ajax call to the Vacancies action method which returns the data needed to build the second dropdown in JSON format. Use this JSON data to build the second dropdown in javascript.

$(function(){
    $("#Company").change(function (e) {
        var $vacancy = $("#vacancy");
        var url = $vacancy.data("url")+'?companyId='+$(this).val();
        $.getJSON(url, function (items) {
            $.each(items, function (a, b) {
                $vacancy.append('<option value="' + b.Value + '">' + b.Text + '</option>');
            });
        });
    });    
});

Now the last part is, implementing the Vacancies method.

public ActionResult Vacancies(int companyId)
{
    var items = db.Vacancies
                  .Where(x=>x.CompanyID==comapnyId)
                  .Select(x => new SelectListItem { Value = x.VacancyId.ToString(),
                                                    Text = x.VacancyName })
                  .ToList();
    return Json(items, JsonRequestBehavior.AllowGet);
}
db

I tried code, but my second list isn't have any values

is it making the ajax call when you do a selection on first dropdown ? Check the network tab in browser dev tools

c# - Make Cascade dropdown List (ASP.NET MVC) - Stack Overflow

c# asp.net asp.net-mvc asp.net-mvc-4
Rectangle 27 2

Here's how I would accomplish something like this. It isn't the only way to do it.

$('#ItemTypeID').on('change', function() {
        $.ajax({
            type: 'POST',
            url: '@Url.Action("GetItemTypeForm")',
            data: { itemTypeId: $('#ItemTypeID').val() },
            success: function(results) {
                var options = $('#ItemTypeFormId');
                options.empty();
                options.append($('<option />').val(null).text("- Select an Item Type  -"));
                $.each(results, function() {
                    options.append($('<option />').val(this.ItemTypeFormId).text(this.Value));
                });
            }
        });
    });

Then you'd have a controller that looks something like this.

[HttpPost]
    public JsonResult GetItemTypeForm(string itemTypeId)
    {
        //pseudo code
        var data = Repostitory.GetData(itemTypeId) 

        return Json(data);
    }

Thank you for taking the time to help me , unfortunately still the third drop down list with the items is empty without any values :(

You'll need to do some debugging, There's tons of potential places your issue could be coming from. The issue can be on the javascript side or the controller side. Put breaks in your controller code and make sure your javascript is calling the appropriate controller method. Then make sure it's getting appropriate lookup id. Then make sure it's sending down the appropriate json (use fiddler or chrome developer tools). If it is then the problem is in how your building the drop down list using javascript. Make sure the this.{your value name} is matching the json result.

c# - three level cascading drop down list - Stack Overflow

c# asp.net asp.net-mvc asp.net-mvc-4
Rectangle 27 2

Update1: Suppose that there is Name ROWID, (and list all the same data source).

using System.Collections.Generic;

namespace MyNamespace
{
    public class MyModel
    {
        public MyModel() { ListA = new List<ListAList>(); }
        public bool Use { get; set; }
        public string Name { get; set; }
        public int? ListAId { get; set; }
        public int? ListBId { get; set; }
        public int? ListCId { get; set; }
        public IList<ListAList> ListA { get; set; }
    }

    public class ListAList
    {
        public int Id { get; set; }
        public string Name { get; set; }
    }

}

Main action in the Home Controller:

public ViewResult MyAction()
{
    var model = new List<MyModel>();
    for (int i = 0; i < 10; i++)
    {
        var item = new MyModel() 
            {
            Name = string.Format("Name{0}", i),
            Use = (i % 2 == 0),
            ListAId = null,
            ListBId = null,
            ListCId = null
            };

        for (int j = 0; j < 10; j++)
        {
            item.ListA.Add( new ListAList() 
                {
                    Id=j,
                    Name = string.Format("Name {0}-{1}",i,j)
                });
        }
        model.Add(item);
    }

    return View(model);
}

Data source provider in the Home controller:

public JsonResult PopulateOption(int? listid, string name)
{

    //todo: preparing the data source filter

    var sites = new[]
    {
        new { id = "1", name = "Name 1" },
        new { id = "2", name = "Name 2" },
        new { id = "3", name = "Name 3" },
    };
    return Json(sites, JsonRequestBehavior.AllowGet);
}
@model MyNamespace.MyModel
<tr>
    <td>@Html.CheckBoxFor(model => model.Use)</td>
    <td>@Html.DisplayFor(model => model.Name)</td>
    <td>@Html.DropDownListFor(model => model.ListAId, new SelectList(Model.ListA, "Id", "Name", Model.ListAId), "", new { @id = string.Format("ListA{0}", Model.Name), @class="ajaxlistA" })</td>
    <td><select class="ajaxlistB" id="ListB@(Model.Name)"></select></td>
    <td><select class="ajaxlistC" id="ListC@(Model.Name)"></select></td>
</tr>

And the main view with Ajax functions:

@using MyNamespace
@model IList<MyModel>

@using (Html.BeginForm("MyAction", "Home")) {
  <table><tr><th>Use?</th><th>Name</th><th>List A</th><th>List B</th><th>List C</th></tr>
@Html.EditorForModel()
</table>
}

<script src="@Url.Content("~/Scripts/jquery-1.7.1.js")" type="text/javascript"></script>


<script>
    $(document).ready( $(function () {
        $('.ajaxlistA').change(function () {
            // when the value of the first select changes trigger an ajax request
            list = $(this);
            var listvalue = list.val();
            var listname = list.attr('id');
            $.getJSON('@Url.Action("PopulateOption", "Home")', { listid: listvalue, name: listname }, function (result) {
                // assuming the server returned json update the contents of the 
                // second selectbox
                var listB = $('#' + listname).parent().parent().find('.ajaxlistB');
                listB.empty();
                $.each(result, function (index, item) {
                    listB.append(
                        $('<option/>', {
                            value: item.id,
                            text: item.name
                        })
                    );
                });
            });
        });
        $('.ajaxlistB').change(function () {
            // when the value of the first select changes trigger an ajax request
            list = $(this);
            var listvalue = list.val();
            var listname = list.attr('id');
            $.getJSON('@Url.Action("PopulateOption", "Home")', { listid: listvalue, name: listname }, function (result) {
                // assuming the server returned json update the contents of the 
                // second selectbox
                var listB = $('#' + listname).parent().parent().find('.ajaxlistC');
                listB.empty();
                $.each(result, function (index, item) {
                    listB.append(
                        $('<option/>', {
                            value: item.id,
                            text: item.name
                        })
                    );
                });
            });
        });
    }));
</script>

Thanks, but I have reviewed some of the links you posted already. My big issue is the fact that I have these cascading dropdown lists in a foreach loop... Causing issues with ids. None of these articles hints at a way to resolve that - at least not what I can infer. Also, I'd like to have these dropdown lists auto bind back to my model. Therefore the Ids need to be correct.

ok, I understand. Questions: (1) Each data sources of list (n x 3 pieces list) is the same: Model.ListA? (2) If yes, then how to filter the data in the second or third list? (3) Do you have any RowId? (Model.Id or something like that, which is based on the lines can be distinguished?)

Thanks SO much for this info. I am just in the middle of another project but will look at this tomorrow and provide feedback.

It appears to work well, the only problem I have is that the ajaxlistB and ajaxlistC entries do not bind back to the data model. The ID generated by MVC for the listAId field is [i].ListAId, with i an incrementing integer. The generated ID for the ajax list items are ListBNamei and ListCNamei, respectively. Do I just need to write out the ID as [i].ListBId and [i].ListCId, respectively, instead?

asp.net mvc - Recommended way to implement array of Ajax cascading dro...

ajax asp.net-mvc razor drop-down-menu cascade
Rectangle 27 6

The following form is a situation where based upon the selected gender (Male or Female), the titles for the gender are displayed (Mr. for Male, Mrs. for female).

Using the Ajax.Begin() helper you can post back to the controller and return values to the view.

All of the data is hard-coded so please forgive the manual adding of the information.

<fieldset>
    <legend>Form</legend>
    @* This will post to the BindTitles method in the Form Controller *@
    @using (Ajax.BeginForm("BindTitles", "Form", new AjaxOptions
    {
        HttpMethod = "POST"
    }))
    {  
        <p>
            @Html.DropDownList("Genders")
        </p>        
        <p>
            <input type="submit" value="Submit" />
        </p>
    }
    <p>
        @Html.DropDownList("Titles")
    </p>
</fieldset>
public ActionResult Form()
    {
        List<string> genderList = new List<string>();
        genderList.Add("Male");
        genderList.Add("Female");
        ViewBag.Genders = new SelectList(genderList);
        ViewBag.Titles = new SelectList(new List<string>());
        return View();
    }

    [HttpPost]
    public ActionResult BindTitles(string genders)
    {
        List<string> titles = new List<string>();
        if (genders == "Male")
        {
            titles.Add("Mr.");
            titles.Add("Sr.");
        }
        else
        {
            titles.Add("Ms.");
            titles.Add("Mrs.");
        }
        ViewBag.Titles = new SelectList(titles);
        List<string> genderList = new List<string>();
        genderList.Add("Male");
        genderList.Add("Female");
        ViewBag.Genders = new SelectList(genderList);
        return View("Form");
    }

asp.net - Cascading DropDown List in MVC 4 - Stack Overflow

asp.net asp.net-mvc entity-framework asp.net-mvc-4 cascadingdropdown
Rectangle 27 1

A CascadingDropDown is really just an extender on a DropDownList, so you should be able to remove the trigger, set your final DropDownList's AutoPostBack property to true, then handle its SelectedIndexChanged event. That should automatically trigger the PartialPostBack so that you can update your GridView accordingly.

<asp:ControlParameter Name="machine_id" ControlID="cddMachine" PropertyName="SelectedValue" />
ControlID
MachineList

When I remove the trigger, and enable autopostback, I get a new error about an invalid postback argument.

After playing around a bit, it seems that I am posting back the text of the drop down list, and not the id. (machine_name vs. machine_id) Any idea as to why that might be?

Perhaps you are binding incorrectly to the DDL. Can you post the code you are using to handle the data? We can look it over.

asp.net - refresh update panel from cascading drop down list - Stack O...

asp.net updatepanel ajaxcontroltoolkit cascadingdropdown
Rectangle 27 1

Looks like this part of your javascript code is beeing executed only on the first load of the page

<script type="text/javascript">

$('#SelectedCampusID').change(function () {
    $(this).parents('form').submit();

 });
</script>

try wiring the change event for #SelectedCampusID using Jquery's on binding. You might also have to do the same for the other dropdowns.

asp.net mvc - How to reset the partial view containing cascading dropd...

asp.net-mvc jquery drop-down-menu cascading
Rectangle 27 2

I think you missed the rest of the variables that arecategory ,country ,subsidiary in script

pass the rest of the values for above fields within <script></script>

Like you passed value for Type like this var type = $('#Type'); you need pass rest of the values.

In Razor you can refer variable by giving that model property

ex: for m.Type can use as ID #Type within script

var category = $('#Category');         var country = $('#Country');         var subsidary = $('#Subsidary');

javascript - search form with cascading dropdown list not working in a...

javascript c# jquery asp.net-mvc asp.net-mvc-4
Rectangle 27 11

I know that this is an old question but somebody still may find it useful

I was searching for the same thing but din't find anything stable and useful so I ended up implementing it by myself:

@using Mvc.CascadeDropDown

//First simple dropdown 
@Html.DropDownListFor(m=>m.SelectedCountry, Model.Countries,
      "Please select a Country", new {@class="form-control"})

//Dropdown list for SelectedCity property that depends on selection of SelectedCountry property
@Html.CascadingDropDownListFor( 
  expression: m => m.SelectedCity, 
  triggeredByProperty: m => m.SelectedCountry,  //Parent property that trigers dropdown data loading
  url: Url.Action("GetCities", "Home"),  //Url of action that returns dropdown data
  actionParam: "country",   //Parameter name for the selected parent value that url action receives
  optionLabel: "Please select a City", // Option label
  disabledWhenParrentNotSelected: true, //If true, disables dropdown until parrent dropdown selected
  htmlAttributes: new { @class = "form-control" }) //Html attributes

I tried this nugget and getting errors using the default ViewBag,propertyIds. How is this used - say in a create form all values for cascadiing dropdowns ( just 2 levels) are from database?

@Diin, Please open an issue in github.com/alexanderar/Mvc.CascadeDropDown/issues that includes some details about your use-case and about the errors that you having. I'll try to resolve it. I used this helper in production for multiple projects, and so fad didn't experience any issues with it. By the way you can see the usage in github.com/alexanderar/Mvc.CascadeDropDown/tree/master/ project

It is a beautiful thing you have done the sample works very well but I think my problem is how to make it pull data from database which has nothing to do with the functionality. Is there a way I could show you my code - Your code works very well but I am looking at making it work from the default mvc scafolding

Hey @AlexArt. what to do if i want to pass more than one ajax paramaetr i have both country id and city id in my parameter list.

Currently library supports only one trigger. One possible solution could be changing value of city dropdown to be combination of countryID_cityID. Then on server simply split the value by _.

razor - Cascading dropdown lists in ASP.NET MVC 5 - Stack Overflow

asp.net-mvc razor cascadingdropdown
Rectangle 27 11

I know that this is an old question but somebody still may find it useful

I was searching for the same thing but din't find anything stable and useful so I ended up implementing it by myself:

@using Mvc.CascadeDropDown

//First simple dropdown 
@Html.DropDownListFor(m=>m.SelectedCountry, Model.Countries,
      "Please select a Country", new {@class="form-control"})

//Dropdown list for SelectedCity property that depends on selection of SelectedCountry property
@Html.CascadingDropDownListFor( 
  expression: m => m.SelectedCity, 
  triggeredByProperty: m => m.SelectedCountry,  //Parent property that trigers dropdown data loading
  url: Url.Action("GetCities", "Home"),  //Url of action that returns dropdown data
  actionParam: "country",   //Parameter name for the selected parent value that url action receives
  optionLabel: "Please select a City", // Option label
  disabledWhenParrentNotSelected: true, //If true, disables dropdown until parrent dropdown selected
  htmlAttributes: new { @class = "form-control" }) //Html attributes

I tried this nugget and getting errors using the default ViewBag,propertyIds. How is this used - say in a create form all values for cascadiing dropdowns ( just 2 levels) are from database?

@Diin, Please open an issue in github.com/alexanderar/Mvc.CascadeDropDown/issues that includes some details about your use-case and about the errors that you having. I'll try to resolve it. I used this helper in production for multiple projects, and so fad didn't experience any issues with it. By the way you can see the usage in github.com/alexanderar/Mvc.CascadeDropDown/tree/master/ project

It is a beautiful thing you have done the sample works very well but I think my problem is how to make it pull data from database which has nothing to do with the functionality. Is there a way I could show you my code - Your code works very well but I am looking at making it work from the default mvc scafolding

Hey @AlexArt. what to do if i want to pass more than one ajax paramaetr i have both country id and city id in my parameter list.

Currently library supports only one trigger. One possible solution could be changing value of city dropdown to be combination of countryID_cityID. Then on server simply split the value by _.

razor - Cascading dropdown lists in ASP.NET MVC 5 - Stack Overflow

asp.net-mvc razor cascadingdropdown
Rectangle 27 2

No, there are no new helpers or methods in MVC 5 to help.

The Ajax HTML helpers have been largely ignored in the update. There are some things that may help with stuff related to this:

  • There is a new @Html.EnumDropDownListFor() HTML helper to populate a dropdown from an Enum.
  • The Attribute routing functionality of the has been improved and now works with the Web API so it is much easier to map URLs to API calls.
@Html.EditorFor(m => m.FieldName, new { htmlAttributes = new { @class = "form-control" } })

I implemented cascading dropdowns last week and used the tried and true JSON call you mentioned. I like to use this jQuery plugin in conjunction with the Web API v2 with the new attribute routing.

razor - Cascading dropdown lists in ASP.NET MVC 5 - Stack Overflow

asp.net-mvc razor cascadingdropdown
Rectangle 27 2

No, there are no new helpers or methods in MVC 5 to help.

The Ajax HTML helpers have been largely ignored in the update. There are some things that may help with stuff related to this:

  • There is a new @Html.EnumDropDownListFor() HTML helper to populate a dropdown from an Enum.
  • The Attribute routing functionality of the has been improved and now works with the Web API so it is much easier to map URLs to API calls.
@Html.EditorFor(m => m.FieldName, new { htmlAttributes = new { @class = "form-control" } })

I implemented cascading dropdowns last week and used the tried and true JSON call you mentioned. I like to use this jQuery plugin in conjunction with the Web API v2 with the new attribute routing.

razor - Cascading dropdown lists in ASP.NET MVC 5 - Stack Overflow

asp.net-mvc razor cascadingdropdown
Rectangle 27 2

Create a view model containing the properties you want to display, including properties for the country and state ID's and a SelectList for the Country options

In your view render selects using @HtmlDropDownFor() for the Country, Sate and Property ID's (the Country select will be populated; the others will be empty)

Using jQuery, in the Country change event, use an AJAX call to an action method which returns a list of States based on the selected Country (either return html to replace the City select, or return JSON to create a new set of option elements.

Repeat the above when a State is selected (to populate the City select)

asp.net mvc - Cascading dripdown list in MVC4 Razor - Stack Overflow

asp.net-mvc asp.net-mvc-3 asp.net-mvc-4 razor razor-2
Rectangle 27 1

Can't do this OOTB but you can create a custom solution. Create an extra column where you track information about your lookups (e.g., the ID of the related item). Use an event receiver on the list and programmatically do the cascade delete.

if you're still around and need a follow up i'm more than happy to help when i'm off work, just let me know.

asp.net - SharePoint 2010 cascade delete with multivalued lookup colum...

asp.net sharepoint sharepoint-2010 lookup
Rectangle 27 1

I have done something similar. Here is some of the code (apologies upfront for this being quite long, but I wanted to make sure you could re-create this on your side):

using Cascading.Models
@model CascadingModel


@{
    ViewBag.Title = "Index";
    Layout = "~/Views/Shared/_Layout.cshtml";
}

<h2>Cascading Forms</h2>
<table>

@using(Html.BeginForm("Index", "Home"))
{
<tr>
    <td>@Html.LabelFor(m=>m.CategoryId)</td>
    <td>@Html.DropDownListFor(m => m.CategoryId, new SelectList(Model.Categories, "Id", "Name"), string.Empty)</td>
</tr>
<tr>
    <td>@Html.LabelFor(m=>m.ProductId)</td>
    <td>@Html.CascadingDropDownListFor(m => m.ProductId, new SelectList(Model.Products, "Id", "Name"), string.Empty, null, "CategoryId", "Home/CategorySelected")</td>
</tr>
<tr>
    <td>&nbsp;</td>
    <td><input type="submit" value="Go"/></td>
</tr>
}
</table>

the Model looks as follows:

public class CascadingModel
{
    public int CategoryId { get; set; }
    public List<Category> Categories { get; set; }
    public int ProductId { get; set; }
    public List<Product> Products { get; set; }
}

the real "clever" part of the system is the Html.CascadingDropDownListFor which looks as follows:

public static class MvcHtmlExtensions
{
    public static MvcHtmlString CascadingDropDownListFor<TModel, TProperty>(
        this HtmlHelper<TModel> htmlHelper,
        Expression<Func<TModel, TProperty>> expression,
        IEnumerable<SelectListItem> selectList,
        string optionLabel,
        IDictionary<string, Object> htmlAttributes,
        string parentControlName,
        string childListUrl
        )
    {
        var memberName = GetMemberInfo(expression).Member.Name;

        MvcHtmlString returnHtml = Html.SelectExtensions.DropDownListFor(htmlHelper, expression, selectList, optionLabel, htmlAttributes);

        var returnString = MvcHtmlString.Create(returnHtml.ToString() + 
                    @"<script type=""text/javascript"">
                        $(document).ready(function () {
                            $(""#<<parentControlName>>"").change(function () { 
                                var postData = { <<parentControlName>>: $(""#<<parentControlName>>"").val() };
                                $.post('<<childListUrl>>', postData, function (data) {
                                    var options = """";
                                    $.each(data, function (index) {
                                        options += ""<option value='"" + data[index].Id + ""'>"" + data[index].Name + ""</option>"";
                                    });
                                    $(""#<<memberName>>"").html(options);
                                })
                                .error(function (jqXHR, textStatus, errorThrown) { alert(jqXHR.responseText); });
                            });
                        });
                     </script>"
                    .Replace("<<parentControlName>>", parentControlName)
                    .Replace("<<childListUrl>>", childListUrl)
                    .Replace("<<memberName>>", memberName));

        return returnString;

    }

    private static MemberExpression GetMemberInfo(Expression method)
    {
        LambdaExpression lambda = method as LambdaExpression;
        if (lambda == null)
            throw new ArgumentNullException("method");

        MemberExpression memberExpr = null;

        if (lambda.Body.NodeType == ExpressionType.Convert)
        {
            memberExpr = ((UnaryExpression)lambda.Body).Operand as MemberExpression;
        }
        else if (lambda.Body.NodeType == ExpressionType.MemberAccess)
        {
            memberExpr = lambda.Body as MemberExpression;
        }

        if (memberExpr == null)
            throw new ArgumentException("method");

        return memberExpr;
    }
}
public ActionResult CategoriesAndProducts()
{
    var viewModel = new CategoriesAndProductsViewModel();
    viewModel.Categories = FetchCategoriesFromDataBase();
    viewModel.Products = FetchProductsFromDataBase();
    viewModel.CategoryId = viewModel.Categories[0].CategoryId;
    viewModel.ProductId = viewModel.Products.Where(p => p.CategoryId).FirstOrDefault().ProductId;
    return View(viewModel);
}

Yes I concur - In the end for me I wasn't using ViewModels correctly. I did know that, but I was foolishly looking for a quick solution. It turned out I wasn't referring to all the other relevant classes in my viewmodel (it was quite a detailed view using a few foreign keys). Once I sorted out the viewmodels I was fine. I'll mark this as the correct answer as it was what I was looking for, but putting the time in to understand viewmodels and returning JSON was what solved it for me. Thanks very much

I've never had to make helpers before so I just made a new class and pasted the code in and added in as many Usings as I could think of but I still having issues with anything including Expression in it and (only this(Html)).SelectExtensions So MemberExp../LambdaExp.../etc all are missing their using. Do you still remember what using are needed?

using System.Linq.Expressions; solved the expression errors now I just need to resolve the html using issue

asp.net mvc 3 - Cascading dropdown lists MVC3 - Stack Overflow

asp.net-mvc-3 entity-framework-4.1