Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Enabling the second and third dropdownlistfor based on the value of first dropdownlistfor in MVC

I have three DropDownLists. If a specific Value from my first DropDownList is chosen, the second Dropdownlist should be enabled. Example, if "Player 3" has been choosen, the other two DropDownList should be enabled, though, if "Player 2" is chosen the last DropDownList should be disabled and the second one enabled.

How can I easily do this? I am using MVC 3 EF model first. This is my code in my view:

 <p>Player</p>
     <div class="editor-field">
        @Html.DropDownListFor(m => m.PlayerName,Model.SubjectTypes, "Choose player" , new { @class = "selectstyle" })
        @Html.ValidationMessageFor(model => model.PlayerName)
    </div>

    <p>Position</p>
    <div class="editor-field">
        @Html.DropDownListFor(model => model.PositionName, Model.Consultants, "Choose Position", new { @class = "selectstyle" })
        @Html.ValidationMessageFor(model => model.ContactPerson)
    </div>

    <p>Team</p>
    <div class="editor-field">
        @Html.DropDownListFor(model => model.TeamName, Model.Teams, "Choose Team", new { @class = "selectstyle" })
        @Html.ValidationMessageFor(model => model.ContactPerson)
    </div>
like image 338
ps__ Avatar asked Mar 20 '12 15:03

ps__


1 Answers

I would do the following in jquery:

$('#PlayerName').change(function() 
{
    var id = $(this).val()
    $.ajax({
        url: '@Url.Action("GetPositions")',
        data:
            {
                "id": id,
            },
        success: function (data)
        {
           $("#positions").html(data);
        }
    });
}

Then i will have in the action controller:

public JsonResult GetPositions(int id)
{
  var positions = Repository.GetPositionsByPlayerId(id);
  var hmtl = positions.Select(x => new SelectListItem
    {
      Value = x.PositionID.ToString(),
      Text = x.Name
    });
  return new JsonResult { Data = html };
}

This will fill the values with all the postions related to that player.

like image 147
jacqijvv Avatar answered Sep 22 '22 15:09

jacqijvv