C-Pfef
C-Pfef

Reputation: 129

MVC 4 Changing a field based on DropDownListFor selection

I have a form that has a dropdownlist that is made up of different course names and a textbox that will contain the number of the next course section based on the dropdown selection and its highest existing section number in the database. After a selection is made the javascript will get called, then call my controller method to figure out which section number it should be, and then fill the textbox.

My dropdownlist: Controller

ViewBag.CourseList = new SelectList(db.CourseLists, "CourseTitle", "CourseTitle");

My dropdownlist: View

@Html.DropDownListFor(model => model.CourseTitle,
                new SelectList(@ViewBag.CourseList, "Value", "Text"), " -- Select Course -- ", new { @id = "CourseTitle", onchange = "CourseChange()" })
@Html.ValidationMessageFor(model => model.CourseTitle)

Textbox:

@Html.EditorFor(model => model.ClassNumber, new { @id = "ClassNumber" })
@Html.ValidationMessageFor(model => model.ClassNumber)

Javascript functions:

<script type="text/javascript">
  function CourseChange() {
      var courseTitle = $('#CourseTitle').val(); //Is always null
      $.getJSON("NextClassNumber", courseTitle, updateClassNumber);
  };

  updateClassNumber = function (data) {
      $('#ClassNumber').val(data);
  };
</script>

When I make a change my method in my controller is called and passes back a value and sets my textbox, but the value for the selected item is coming through as null. Any ideas as to why?

::::EDIT::::

@model QIEducationWebApp.Models.Course

@{
    ViewBag.Title = "Add New Course";
}

<script src="@Url.Content("~/Scripts/jquery.validate.min.js")" type="text/javascript"></script>
<script src="@Url.Content("~/Scripts/jquery.validate.unobtrusive.min.js")" type="text/javascript"></script>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<script src="//netdna.bootstrapcdn.com/bootstrap/3.1.1/js/bootstrap.min.js"></script>   
<script src="//ajax.aspnetcdn.com/ajax/jquery.validate/1.11.1/jquery.validate.min.js"></script>
<script src="//ajax.aspnetcdn.com/ajax/mvc/4.0/jquery.validate.unobtrusive.min.js"></script>


<script type="text/javascript">
    $(function () {
        $('#CourseTitle').on('change', function () {
            var courseTitle = $(this).val();
            $.ajax({
                url: '@Url.RouteUrl(new{ action="NextClassNumber", controller="Course"})',
                data: { courseTitle: courseTitle },
                type: 'get'
            }).done(function (data) {
                $('#ClassNumber').val(data);
            });
        });
    });

</script>

<h1 class="page-header">@ViewBag.Title</h1>

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

    <table class="table">
        <tr>
            <th class="table-row">
                Course Title:
            </th>
            <td class="table-row">
                @Html.DropDownListFor(model => model.CourseTitle1,
                    @ViewBag.CourseList as SelectList, " -- Select Course -- ", new { @class="form-control", @id="CourseTitle" })
                @Html.ValidationMessageFor(model => model.CourseTitle)
            </td>
        </tr>
        <tr>
            <th class="table-row">
                Class Number:
            </th>
            <td class="table-row">
                @Html.EditorFor(model => model.ClassNumber, new { @id = "ClassNumber" })
                @Html.ValidationMessageFor(model => model.ClassNumber)
            </td>
        </tr>
        <tr>
            <th class="table-row">
                Course Type:
            </th>
            <td class="table-row">
                @Html.DropDownList("CourseType", " -- Select Type -- ")
                @Html.ValidationMessageFor(model => model.CourseType)
            </td>
        </tr>
        <tr>
            <th class="table-row">
                Start & End Date:
            </th>
            <td class="table-row">
                @Html.EditorFor(model => model.CourseStartDate)
                @Html.ValidationMessageFor(model => model.CourseStartDate)
            </td>
            <td class="table-row">
                @Html.EditorFor(model => model.CourseEndDate)
                @Html.ValidationMessageFor(model => model.CourseEndDate)
            </td>
        </tr>
        <tr><td class="table-row-blank"></td></tr>
        <tr>
            <td class="table-row-button">
                <input class="button" type="submit" value="Create" />
                <input type="button" class="button" value="Cancel" 
                    onclick="location.href='@Url.Action("Index")'" />
            </td>
        </tr>
    </table>
}


@section Scripts {
    @Scripts.Render("~/bundles/jqueryval")
}

Upvotes: 0

Views: 4589

Answers (2)

JamieD77
JamieD77

Reputation: 13949

your code should work fine if the select list is being generated correctly.

I would use part of the suggestion above and use

@Html.DropDownListFor(model => model.CourseTitle,
            (SelectList)ViewBag.CourseList,
            " -- Select Course -- ",
            new { onchange = "CourseChange()" })

using another good suggestion already mentioned you can change your script to use on instead

<script type="text/javascript">
    $(function () {
        $('#CourseTitle').on('change', function () {
            var courseTitle = $(this).val();
            $.getJSON("NextClassNumber", courseTitle, function (data) {
                $('#ClassNumber').val(data);
            });
        });
    });
</script>

here is a dotnetfiddle example. DotNetFiddle

Upvotes: 1

Ehsan Sajjad
Ehsan Sajjad

Reputation: 62488

You can pass reference of dropdownlist from the onchange event :

onchange = "CourseChange"

and in js function:

function CourseChange(element) {

    var selected = element.Value;
    // or
    var selected = $(element).val();

and a side note you don't need to construct SelectList again on View just cast it from ViewBag:

@Html.DropDownListFor(model => model.CourseTitle,
                      @ViewBag.CourseList as SelectList,
                      "-- Select Course --",
                      new { onchange = "CourseChange" })

Upvotes: 1

Related Questions