asp.net/MVC 3/razor/jquery/cascading dropdown list not working
Asked Answered
P

1

1

I'm new to stackoverflow as well as to jquery/javascript. I've been searching all day for different ways to add cascading drop down lists to my current project and have yet to find a way that has worked for me. Most of my finding have been from out of date and based upon MVC 2 to webforms to older technologies. I did find a few tutorials and posts based upon MVC 3/4 that have helped but I'm still about to chunk my mouse at my computer screen.

Some links that I've looked at for help are: Radu Enuca's Tutorial on cascading dropdown lists and Rick_Anderson's Tutorial

Some background on the project:

I'm creating a work ticket system for employees to submit their daily time to the office. I have a controller, view, and jquery script listed below.

Controller

public class WorkTicketController : Controller
{
    private Context db = new Context();

    public ActionResult GetClientReps(int id)
    {
        var Reps = from c in db.ClientReps
                   where c.ClientID == id
                   select c;

        List<SelectListItem> clientReps = new List<SelectListItem>();

        foreach (var item in Reps)
        {
            string clientRepId = item.ClientRepID.ToString();

            string clientRepName = item.FirstName + " " + item.LastName;

            clientReps.Add(new SelectListItem(){ Value = clientRepId, Text = clientRepName });
        }

        var List = new SelectList(clientReps, "Value", "Text");

        return Json(List, JsonRequestBehavior.AllowGet);
    }

    public ActionResult Create()
    {
        ViewBag.Clients = GetGlobalItems.ClientList();
        ViewBag.Supervisors = GetGlobalItems.UserListByRole("Supervisor");

        return View();
    }

    protected override void Dispose(bool disposing)
    {
        db.Dispose();
        base.Dispose(disposing);
    }
}
}

View

@model NewbyPortal.Models.WorkTicket

@{
ViewBag.Title = "Create";
}
<article>
<div class="linearBg1">Create Daily Work Ticket</div>
<br />

@using (Html.BeginForm()) {
    @Html.ValidationSummary(true)
    <div class="linearBg1">
        General Information
    </div>
    <div class="section-span-body">
        <table>
            <tr class="empTableRowBody2">
                <th class="empTableRowBody2">
                    @Html.LabelFor(Model => Model.DateWorked) *
                </th>
                <th class="empTableRowBody2">
                    @Html.LabelFor(Model => Model.PayKey)
                </th>
                <th class="empTableRowBody2">
                    @Html.LabelFor(Model => Model.PONumber)
                </th>
                <th class="empTableRowBody2">
                    @Html.LabelFor(Model => Model.WONumber) *
                </th>
            </tr>
            <tr>
                <td>
                    @Html.EditorFor(Model => Model.DateWorked)
                </td>
                <td>
                    @Html.EditorFor(Model => Model.PayKey)
                </td>
                <td>
                    @Html.EditorFor(Model => Model.PONumber)
                </td>
                <td>
                    @Html.EditorFor(Model => Model.WONumber)
                </td>
            </tr>
            <tr class="empTableRowBody2">
                <th class="empTableRowBody2">
                    @Html.LabelFor(Model => Model.ProjectId)
                </th>
                <th class="empTableRowBody2">
                    @Html.LabelFor(Model => Model.ClientID)
                </th>
                <th class="empTableRowBody2">
                    @Html.LabelFor(Model => Model.ClientRepID)
                </th>
                <th class="empTableRowBody2">
                    @Html.LabelFor(Model => Model.SupervisorID) *
                </th>
            </tr>
            <tr>
                <td>
                    @Html.TextBoxFor(Model => Model.ProjectId)
                </td>
                <td>
                    @Html.DropDownList("ClientID", ViewBag.ClientID as SelectList, "Select a Client", new { id = "drop1" })
                </td>
                <td>
                    <select id="drop2"></select>
                </td>
                <td>
                    @Html.DropDownList("SupervisorID")
                </td>
            </tr>
            <tr class="empTableRowBody2">
                <th colspan="2" class="empTableRowBody2">
                    @Html.LabelFor(Model => Model.JobLocation) *
                </th>
                <th colspan="2" class="empTableRowBody2">
                    @Html.LabelFor(Model => Model.JobDescription) *
                </th>
            </tr>
            <tr>
                <td colspan="2">
                    @Html.TextBoxFor(Model => Model.JobLocation, new{@class="textboxlengthlong"})
                </td>
                <td colspan="2">
                    @Html.TextBoxFor(Model => Model.JobDescription, new{@class="textboxlengthlong"})
                </td>
            </tr>
        </table>
    </div>
    <div class="section-span-footer"></div>
    <p>
        <input type="submit" value="Next" />
    </p>
}

Script

<script type="text/javascript">
$(document).ready(function () {
    $("#drop1").change(function () {
        var id = $(this).val();
        $.getJSON("/WorkTicket/GetClientReps/", { id: id },
            function (data) {
            var select = $("#drop2");
            select.empty();
            select.append($('<option/>', {
                value: 0,
                text: "Select a Client Rep"
            }));
            $.each(data, function (index, data) {

                select.append($('<option/>', {
                    value: data.Value,
                    text: data.Text
                }));
            });
        });
    });
});    
</script>

When I choose a Client from the Client drop down list, nothing happens for the Client Rep drop down list. I know it must be something obvious that I'm missing but at this point I don't mind looking like an idiot to solve this frustrating problem.

I have verified that that other jquery works in my project so I don't have anything disabled as far as I can tell.

Thank you in advance for the help!

T

Update

So I have made one step forward it appears. I started moving my script placement around on the view. I tried the top and the bottom of the page. I also reviewed the layout page to make sure I was link to the right jquery libraries. That all checked out but it got me thinking so I moved my script into it's own custom.js file and linked to it on the layout page and the cascading drop down lists started working.

My next question is why? and should I leave it the way it is now? Thanks!

T

Paternity answered 28/9, 2012 at 23:52 Comment(2)
I made a typo on the view for the client drop down list. The Viewbag should be Viewbag.Clients, not Viewbag.ClientIDPaternity
I've also verified that my GetClientReps action is returning the propper jsonPaternity
F
1

Ok -> The Viewbag should be Viewbag.Clients, not Viewbag.ClientID

@Html.DropDownList("ClientID", ViewBag.ClientID as SelectList, "Select a Client", new { id = "drop1" })

<select id="drop2"></select>

And the same for this...

@Html.DropDownList("SupervisorID")

jQuery code is Ok.

Try this, and then fill with your code:

Create.cshtml

@{
    ViewBag.Title = "Create";
}

<script type="text/javascript">
    $(document).ready(function () {
        $("#drop1").change(function () {
            var id = $(this).val();
            $.getJSON("/WorkTicket/GetClientReps/", { id: id },
            function (data) {
                var select = $("#drop2");
                select.empty();
                select.append($('<option/>', {
                    value: 0,
                    text: "Select a Client Rep"
                }));
                $.each(data, function (index, data) {

                    select.append($('<option/>', {
                        value: data.Value,
                        text: data.Text
                    }));
                });
            });
        });
    });    
</script>




<div class="linearBg1">Create Daily Work Ticket</div>
<br />

@using (Html.BeginForm())
{
    @Html.ValidationSummary(true)

    @Html.DropDownList("ClientID", ViewBag.Clients as SelectList, "Select a Client", new { id = "drop1" })
    <select id="drop2"></select>



    <div class="section-span-footer"></div>
    <p>
        <input type="submit" value="Next" />
    </p>
}

WorkTicketController

public class WorkTicketController : Controller
{
    //
    // GET: /WorkTicket/

    public ActionResult Index()
    {
        return View();
    }

    private Context db = new Context();

    public ActionResult GetClientReps(int id)
    {
        /*var Reps = from c in db.ClientReps
                   where c.ClientID == id
                   select c;
        */
        List<SelectListItem> clientReps = new List<SelectListItem>();

        /*foreach (var item in Reps)
        {
            string clientRepId = item.ClientRepID.ToString();

            string clientRepName = item.FirstName + " " + item.LastName;

            clientReps.Add(new SelectListItem() { Value = clientRepId, Text = clientRepName });
        }*/

        clientReps.Add(new SelectListItem() { Value = "10", Text = "name" });

        var List = new SelectList(clientReps, "Value", "Text");

        return Json(List, JsonRequestBehavior.AllowGet);
    }

    public ActionResult Create()
    {
        List<SelectListItem> clientReps = new List<SelectListItem>();
        clientReps.Add(new SelectListItem() { Value = "1", Text = "client 1" });
        clientReps.Add(new SelectListItem() { Value = "2", Text = "client 2" });
        ViewBag.Clients = new SelectList(clientReps, "Value", "Text");
        //ViewBag.Supervisors = GetGlobalItems.UserListByRole("Supervisor");

        return View();
    }

    protected override void Dispose(bool disposing)
    {
        //db.Dispose();
        base.Dispose(disposing);
    }

}
Frisby answered 29/9, 2012 at 0:22 Comment(5)
Sorry, that was a typo on my part. The ClientID and SupervisorID have already been changed to Clients and Supervisors but with no luck in solving the problem! Thank you for the quick response!Paternity
Please, try again with this example.Frisby
I got it working by moving my script to it's own .js file and then linking to it from the layout page. Any thoughts on why this fixed it vs calling the script via the <script> tag directly on the view?Paternity
Excuse my English, the problem is when it was running the $ (document). Ready (function ()). It would be better if you use a file "WorkTicket.js" with jQuery query, and linked from the View.Frisby
Thanks Mate! That worked great linking from the View. Your help was greatly appreciated!Paternity

© 2022 - 2024 — McMap. All rights reserved.