Code Monkey home page Code Monkey logo

mvc.cascadedropdown's People

Contributors

alexanderar avatar li-yanzhi avatar mocella avatar pjotrb avatar scottbabcock avatar zyrconium13 avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

mvc.cascadedropdown's Issues

Ampersand breaking cascades

When the selected value has an ampersand in the text, it breaks the value retrieve for the child.

For example, I select 'PH&T', the value the controller action receives is just 'PH', thus none of the child options populate.

Any suggestions?

Using Entity framework

I'm trying to use this library with Entity framework model binding but I can't get the cascading dropdown to respond when I am selecting anything from the parent one, it's always disabled.

Controller.cs

// GET: Improvements/New
public ViewResult New()
{
    var dbAreas = _context.ImprovementAreas;
    var viewModel = new NewImprovementViewModel
    {
        Improvement = new Improvement(),
        Areas = dbAreas.Select
            (a => new SelectListItem { Text = a.Name, Value = a.Id.ToString() }).ToList()
    };
    return View(viewModel);
}
...
public JsonResult GetSubAreas(int areaId)
{
    var dbSubAreas = _context.ImprovementSubAreas.Where(
        sub => sub.ImprovementArea.Id == areaId).ToList();
    var subAreas = dbSubAreas.Select(
        sub => new SelectListItem { Text = sub.Name, Value = sub.Id.ToString() }).ToList();
    return Json(subAreas, JsonRequestBehavior.AllowGet);
}

New.cshtml

<div class="form-group">
    @Html.LabelFor(m => m.Improvement.ImprovementAreaId)
    @Html.DropDownListFor(m => m.Improvement.ImprovementArea,
    Model.Areas, "Select area", new { @class = "form-control" })
</div>
<div class="form-group">
    @Html.LabelFor(m => m.Improvement.ImprovementSubAreaId)
    @Html.CascadingDropDownListFor(
    expression: m => m.Improvement.ImprovementSubArea,
    triggeredByProperty: m => m.Improvement.ImprovementAreaId,
    url: Url.Action("GetSubAreas", "Improvements"),
    ajaxActionParamName: "areaId",
    optionLabel: "Select subarea",
    disabledWhenParrentNotSelected: true,
    htmlAttributes: new { @class = "form-control" })
</div>

ViewModel

public Improvement.Improvement Improvement { get; set; }
public IEnumerable<SelectListItem> Areas { get; set; }

The other models have navigation properties tied to them so thats what I'm trying to set but it doesn't seem to work. Do I have to just use simple string properties in the view model like in the example and then bind everything in the POST request to the controller or is there a nice way to do this?

I also don't understand what the ajaxActionParamName refers to exactly?

Initial load

Hello,

Great helper, but there appears to be no possibility to load initial data without using javascript. How can I get the dropdowns to load with lists from the first form load?

Action sample

Hi,

Could you please provide sample of the action method

I tried something like this, but the dropdown list has (in my case of 2 integer) 2 blanks item.

 public ActionResult GetProcesses(int organization)
        {
            db.Configuration.ProxyCreationEnabled = false;
            //IList<PROCESSES> test = new List<PROCESSES>();
            //test = db.ORGS_PROCESSES.Where(o=>o.ID_ORGANIZATION_ASSIGNMENT.Equals(organization)).Select(s=>s.PROCESSES).ToList();
            //ViewData["processes"] = test;
            //  return Json(test, JsonRequestBehavior.AllowGet); 
            // return View();
            IList<int> iList = new List<int>();
            iList.Add(1);
            iList.Add(2);
           
            return Json(iList, JsonRequestBehavior.AllowGet);

        }

thanks and best regards,

Selected item posting "null"

Hi,
I've successfully implemented the cascading drop down menus and they work fine, except when I post the form the value of the selected item in the second drop down list (in your example it would be SelectedCity) is always "null", my guess is that this value is being set to null at some point earlier on and not getting updated to the selected value once a change is made.

Problem with validation

Hi, I have a problem with jquery validation. I am using the option "disabledWhenParentNotSelected" with some drop down list; the last one is required for my model but the rest no. The problem is that I select an option in the first ddl, the second is enabled but the rest no so if a click on submit button, the form is send because my last ddl is disabled and validation can't read it. I have been testing and I have been observed that if ddl have attributte "readonly" instead "disabled" this field is validated. ¿There is any way to change disabled by readonly when I set disabledWhenParentNotSelected: true or something similar?

Thanks a lot.

CSS dependency observed.

HI Dear,
I have used this cascadeDropDown and it works fine but I'm facing one problem. I have checked that if I put @Class="selectpicker" rather than "form-control" it do not render data in cascadedDropdown.
I can not use form-control ...
I have seen in inspect element, values are there but are not showing up just because of this class selectpicker. However with razor dropdownlistfor it works with this css class perfect.

Force the change trigger through jquery

Is it possible to force the change trigger on a parent element? For example, say I have a parent and a child dropdown. I select an item from the parent and the child loads the data and then I select a child. Once I click a button to add them to a table, I sometimes have trouble "resetting" the elements. If I set the value of the parent to the "" element, the data from the child still exists. I have tried using:

$("#elementID").val("")

as well as

var test = document.getElementById("elementID");
var testoption = $("#elementID option");
var testVal = testoption.filter(function() {return $(this).html() === "Default Select Text"}).val();
test.value = testval;

Sometimes I can get it to properly reset and sometimes the child data is still loaded until I manually change the parent's selected item.

Possible NullReferenceException when using Nested Classes in Model

tl;dr
When the expression argument is for a property on a sub-model, such as Model.Address.SelectedCity, and the model is instantiated but the submodel is null, rendering will fail with a NullReferenceException.

Detail:
When evaluating the current property value during render so that it can be pre-selected in the drop-down, rendering can fail if the property is on an uninstantiated sub-class / sub-model.

If the control's expression argument is for a property that is directly on the model such as Model.SelectedCity, and the model is null, the control handles the null model instead of throwing. However, if the model is instantiated, but the control's expression argument is for a property on a sub-model such as Model.CurrentAddress.SelectedCity, and the submodel is null, evaluating the expression throws a NullReferenceException and rendering fails.

namespace Mvc.CascadeDropDown.Test.Models
{
    using System.ComponentModel.DataAnnotations;
    using System.Web.Mvc;

    public class CascadingDropdownsModel
    {
        public IList<SelectListItem> Countries { get; set; }

        public AddressModel CurrentAddress { get; set; }
    }

    public class AddressModel
    {
        [Required]
        public string SelectedCountry { get; set; }

        [Required]
        public string SelectedCity { get; set; }

        [Required]
        public int? SelectedStreet { get; set; }
    }
}
        public ActionResult Index()
        {
            var model = new CascadingDropdownsModel
            {
                Countries =
                    new List<SelectListItem>
                    {
                        new SelectListItem
                        {
                            Text = "US",
                            Value = "US"
                        },
                        new SelectListItem
                        {
                            Text = "UK",
                            Value = "UK"
                        },
                    },
                CurrentAddress = null
            };
            return View(model);
        }
        <div class="form-group">
            @Html.CascadingDropDownListFor(expression: m => m.CurrentAddress.SelectedCity,
                                triggeredByProperty: m => m.CurrentAddress.SelectedCountry,
                                url: Url.Action("GetCities", "Home"),
                                ajaxActionParamName: "country",
                                disabledWhenParentNotSelected: true,
                                htmlAttributes: new { @class = "form-control" },
                                options: new CascadeDropDownOptions
                                {
                                    BeforeSend = "beforeSend",
                                    HttpMethod = "post",
                                    OnCompleteGetData = "onComplete",
                                    OnFailureGetData = "onFailure",
                                    OnSuccessGetData = "onSuccess"
                                })
            @Html.ValidationMessageFor(m => m.CurrentAddress.SelectedCity)
        </div>

The exception is thrown within GetPropStringValue when the control is attempting to get the current value of the property.

private static string GetPropStringValue<TModel, TProp>(TModel src, Expression<Func<TModel, TProp>> expression)

Expected Behavior:
The control handles the NullReferenceException when evaluating the expression argument, returning an empty string similar to when the model is null, and allowing the page to fully render.

Cascading DropDown, that can take options to avoid Duplicate Combinations

Hi, thanks for this great control.

for e.g. if we have a Table with cascading drop downs, no two combinations should be repeated or duplicated. So the check usually happens on the OnChange of the seconddropdown in the cascading dropdown

In cases where I have rows of cascading dropdowns, I often face a requirement where the user should not be allowed to pick the same combination of selections across the rows.

VB.NET environment excample

Do you have any examples using this in a VB environment? I'm having some trouble getting the syntax to work. thanks.

Not passing value to controller anymore

I have multiple CDDs in multiple partial views. I am assigning them independent ID's based on the partial that was loaded, and I load the partial view items into a html.beginCollection.

This was working a few months ago but suddenly stopped working. The value correctly exists in the correct CDD all the way until it is submitted to the controller, where it loses its value and is set to NULL. I ensured that my functions are mapping correctly by using a hiddenFor and seeing if I can map a value through to the controller and it works fine.

I cannot post code because it is hosted on another intranet system.

I have a Drop Down List, a CDD that triggers off that, another CDD that triggers off that, and another CDD that triggers off that.

The CDDs have the value mapped to it "Html.CDDFor(m => m.CDDItemOne.... , new{@id="CDDItemOne"+suffix})

where suffix is generated upon loading the partial view.

Anyone have any ideas at what I can try?

What if the 'First simple dropdown' has an Id

I tried this library, but if the code is like this one:

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

//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
  ajaxActionParamName: "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

Then the first dropdown code generated loses its "Id" attribute:
<select id="someId_123456789" ...

And then the javascript fails because it doesn't find the element:
var triggerElement = document.getElementById('SelectedCountry');//null value

How this problem could be solved? Which is the way to set a specific Id in triggeredByProperty?

Using a modal with cascading DDL odd bug

So I have a page that I am loading the data through a serialized json object into a view model that loads the page data. However, when I load the modal to edit a line item in my table, the cascading dropdown menu does not load the data. However when closing the modal and reloading it, the first of 3 cascading DDL populates. Continuing to close and reopen the modal results in more and more CDDL to load the data.

I am not sure what the issue is. I have spent days trying different solutions. The data looks correct. The only thing I can see is that there are two options with 'selected' = true, but when I manually set the correct one to be the only 'selected', it still does not load the data at all.

Question: Preset selections upon page load

I have tried a few different ways to try and get my dropdown lists to load with an option already selected but fail every time. Do I set up a new cascadingdropdown model and set the selected options there in the controller before I send to the view or is there another way?

I am using Distinct for my dropdowns because of the way our DB is set up to get the locations, trying to set a value while using Distinct usually just auto-selects the first option because it cannot find the option I specified even though it is clearly there, just filtered (I know, the index is shifted in distinct from my preset value).

Problems with model inside model

Hi,

I have a model that bind fields on Razor. My model have another model with fields to dropdown.

Example:
class Class1() { Classe 2 };
class Classe2() { country, city, street}

In razor the dropdown Id is 'classe2_country' but the identifier to triggered is document.getElementById('county').

How I resolve this problem?

Thanks

Nuno Rebocho

Implementing Create.cshtml in real world application

I really try hard to implement your nuget helper. But my cascading DropDownListFor (the dependant one) does not show anything. I think it is because of my ActionResult. Would you be nice enough to help? p.s. I did read all your stuff from GitHub Mvc.CascadeDropDown, but cannot understand some. A tutorial for dummies would be great (I'm new to this stuff.)

So, this is my PlacesController.cs ActionResult:
`public ActionResult GetRegionsByPaysId(int paysId)
{
var region = from r in db.Region
where r.IdPays == paysId
select r;

        return Json(new SelectList(region.ToArray(),
            "IdRegion", "NomRegion"), JsonRequestBehavior.AllowGet);
    }`

Now my Create.cshtml:
@Html.CascadingDropDownListFor( expression: model => model.IdRegion, triggeredByProperty: model => model.IdPays, url: Url.Action("GetRegionsByPaysId", "Places"), ajaxActionParamName: "paysId", optionLabel: "", disabledWhenParrentNotSelected: true, htmlAttributes: new { @class = "form-control" })

Now my Models.cs (without the { get; set;} and yaketiyak)
`public partial class Place
{
public int IdPlace
public string NamePlace
public int IdPays
public int IdRegion

    public virtual Pays Pays
    public virtual Region Region
}

public partial class Pays
{
public int IdPays
public string CodePays
public string NamePays

    public virtual ICollection<Place> Place 
    public virtual ICollection<Region> Region
}

public partial class Region
{
public int IdRegion
public int IdPays
public string NameRegion
public string CodeRegion

    public virtual Pays Pays
    public virtual ICollection<Place> Place
}`

Thanks in advance, me.
p.s. What is ajaxActionParamName?

Disabled elements

Hi,
I'm adding some elements to the cascadeDropDownList, using this action in the controller:

            var courseList = new List<SelectListItem>();
            foreach(var course in courses)
            {
                _breadcrumb += "-";
                courseList.Add(new SelectListItem
                {
                    Value = course.ID.ToString(),
                    Text = _breadcrumb + " " + course.Text,
                    Disabled = course.Disabled // WARNING!!!! It looks like the NuGet MVC.CascadeDropDownList package does not support disabled state, must investigate further
                });
                courseList.AddRange(_FlattenCoursesTree(course.Courses));
                _breadcrumb = _breadcrumb.Remove(_breadcrumb.Length - 1);
            }
            return Json(courseList, JsonRequestBehavior.AllowGet);

In the View it's consumed like that:

@Html.CascadingDropDownListFor(model => model.DegreeCourseId, "MainDegreeCourseId", Url.Action("GetCourses", "RegistrationForms"), "course", "", true, new { @class = "form-control" })

It works as far as data loading is performed and I can see the populated items in the CascadingDDL, but this library seems not to use the Disabled value.

Is there something I'm missing?

Thank you very much

Using in multiple partial view

Hi Alexanderar/Author,

Thanks for provide such helper that can easily build a cascading dropdownlist, while in my case I'm having multiple partial views (can be add/remove by user) and there is a pair of cascade ddl in each one of them, structured like

-Main View

  • PV1 - 2 DDL
  • PV2 - 2 DDL
    ......

Only the DDLs in PV1 (Partial View 1) is cascading, yet others not functioning, after selecting first ddl the second ddl is not retrieving the related data. The code of ddls in PV are below,

@Html.DropDownListFor(m => m.Type, Model.ConditionTypes, "Please select a Country", new { @class = "form-control", id = "Type", name = "Type" })

    @Html.CascadingDropDownListFor(expression: m => m.Operator,
                            triggeredByProperty: m => m.Type,
                            url: Url.Action("GetOperator", "Job"),
                            ajaxActionParamName: "type",
                            optionLabel: "Please select a City",
                            disabledWhenParrentNotSelected: false,
                            htmlAttributes: new { @class = "form-control", id= "Operator", name = "Operator" })

I was wondering the cause might be these ddls having same id/name across partial views? Is it possible using Mvc.CascadeDropDown across multiple partial views?

Thanks in advance.

Tim.

Multiple Dropdowns dependent on same "Master"

Hello,
Exellent control, but I have one issue.
I am trying to create a page with multiple DropDowns.
I create the page with three controls. A, B and C. A is independent. B is dependent on A, and C is dependent on A and B. Everything works as expected.

I now add dropdown D and make it dependent on A. D works, but B (and therefore C) is not working anymore.

Is there a way to make this work?

Anders

Can't get Overload for CascadingDropDownList() to work

Nice work with this package. It could save many hours of coding if I could overcome one last hurdle.
I have been able to get CascadingDropDownListFor() to work however the way I display and bind my dropdownlists follows the pattern @Html.DropDownList("ProjectTypeID", Model.ProjectTypeList).

This VB.NET Razor code works:
@Html.CascadingDropDownListFor(expression:=Function(x) x.AreaList, triggeredByProperty:=Function(x) x.ProjectTypeID, url:=Url.Action("GetAreaByTType", "Project"), ajaxActionParamName:="TType")

Your test project only shows tests for the CascadingDropDownListFor() overload. I feel like the translation should be simple however I keep getting the error: Overload resolution failed because no accessible....

Thank you

parameter name misspelled

you are spelling a parameter like this:
disabledWhenParrentNotSelected
should be:
disabledWhenParentNotSelected

Determine when the data is loaded

I am working on a project that is utilizing this and I have an issue that I am trying to work on/optimize. The idea is that you can select a location (hierarchy is floor/room/cube) that utilizes the cascade or be able to select a user and auto populate the cascade. My issue is that initially the data isn't loaded and when I try to set the values, obviously we run into errors. So I started to use a delay of setting the drop downs that rely on the previous. It... works but obviously is not very well optimized, for example if the program is slow, the delay might not be enough. Is there a way of determining the exact point in which the data is loaded?

Disable Caching

Is there a way to disable caching? For example, on another maintenance screen a column is added to the database. The user navigates to the page with the CDD and selects an option for the first level CDD, and looks through the list of items in the second level CDD, but does not see the new item that was added. When the user closes the browser and reopens, they can now see the new item. Browser IE11.

The type 'MvcHtmlString' is defined in an assembly that is not referenced. You must add a reference to assembly 'System.Web.Mvc, Version=3.0.0.0

I'm getting the error below when I setup a dropdownlist in my .Net Core project. Does this only work with MVC 3.0?

Error CS0012 The type 'MvcHtmlString' is defined in an assembly that is not referenced. You must add a reference to assembly 'System.Web.Mvc, Version=3.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35'. AppsAdmin \filesvr02\adpis\Company\ISShared\Christian King\AppsAdmin\AppsAdmin\Pages\ImprovisImport.cshtml 11 Active
Annotation 2019-11-21 134245

Not working in IE-8,9,10

Hello ,

This nice and helpful Mvc.CascadeDropDown is not working on IE-8,9,10. (Works great with IE-11)

I am posting this because i could not see any documentation related to supported browsers for Mvc.CascadeDropDown.

Following are errors per IE version:

IE- 8:
Object doesn't support property or method 'createEvent'

IE-9 and 10:
Unable to get property 'cascadeDdUrl' of undefined or null reference

support for IE-8,9,10 would be great for people still using older versions of IE.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.