Basic site setup

1. Add a reference to Detergent.dll in your MVC project.

2. Add the jquery.detergent-1.0.js script to your site's scripts directory.

3. Make sure to add the script to the page you're going to use it on!

4. In your Global.asax.cs file, in the Application_Start event, you need to change the current ModelMetadataProvider to a new instance of CustomModelMetadataProvider.
ModelMetadataProviders.Current = new CustomModelMetadataProvider();

This is required so we can add CascadingAttribute instances to the model metadata.

Using CascadingAttribute

Below is an example of a very simple setup. StateId is the "parent", it represents the dropdown that must have a value that the child dropdown can filter its values by. Action and DependsOn are both required fields.

using rossisdead.Mvc.Detergent;

public class ViewModel 
{
    public int? StateId { get; set; }
   
    [Cascading(Action="/Town/GetTownsById/", DependsOn="StateId")]
    public int? TownId { get; set; }
}

Setting up your controller

using rossisdead.Mvc.Detergent;

public class Town 
{
    public int TownId { get; set; }
    public string Name { get; set; }
}

public class TownController : Controller
{
    [HttpGet]
    public CascadingActionResult GetTownsById(int townId) 
    {
        IEnumerable<Town> towns = DoSomethingToGetTowns(townId);
        var result = new CascadingActionResult();
        result.Data = towns;
        result.TextField = "Name";
        result.ValueField = "TownId";
        result.JsonRequestBehavior = JsonRequestBehavior.AllowGet;
        return result;
    }
}

Setting up your View

@using rossisdead.Mvc.Detergent
@model ViewModel

<script src="/path/to/jquery.detergent-1.0.js"></script>

@* Setup your parent dropdown like you would any other dropdown. *@
@Html.DropDownListFor(m => m.StateId, someListOfStates)

@* Use the CascadingDropDownFor extension method to make the cascading magic work! *@
@Html.CascadingDropDownFor(m => m.TownId)

Last edited Feb 17, 2012 at 10:11 PM by rossisdead, version 7

Comments

No comments yet.