Rilcon42
Rilcon42

Reputation: 9763

Use drop down result to filter another dropdown C# MVC

I am trying to update a drop down based on the users selection in the first drop down. I found this SO post on the topic, but Im not quite sure how to add the jquery to filter values to my Razor view. Can someone point me in the right direction?

My view so far:

@using System.Security.Claims;
@model UpdateClaimFormModel;

<h2>UpdateClaimView</h2>
@using (@Html.BeginForm())
{
    <select name="emailcheese">
        <option selected disabled>Select User</option>
        @foreach (var i in Model.UserNames)
        {
            <option>@i.ToString()</option>
        }
    </select>
    <select name="authpolicy">
        <option selected disabled>Select Claim:</option>
        @foreach (var i in Model.UserClaims)
        {
        <option>@i.Type.ToString()</option>
        }
    </select>
    <div class="form-group">
        <button type="submit" class="btn btn-default">Whoo</button>
    </div>
}

My Goal:

Select User [bob, bill, jim]

Select Claim: If user bob:[1,2,3], If user bill:[1,4,8], If user him:[4,5,6]

Upvotes: 0

Views: 1808

Answers (1)

RAHUL S R
RAHUL S R

Reputation: 1579

so simpley you can do something like this

@using (@Html.BeginForm())
{
    <select name="emailcheese" id="selectUserNames">
        <option selected disabled>Select User</option>
        @foreach (var i in Model.UserNames)
        {
            <option>@i.ToString()</option>
        }
    </select>
    <select name="authpolicy" id="selectAuthPolicy"> 
    </select>
    <div class="form-group">
        <button type="submit" class="btn btn-default">Whoo</button>
    </div>
}

now in the script part

$(function(){
 var userClaims = @Html.Raw(Json.Encode(Model.UserClaims));

 $(document).on('change','#selectUserNames'function(){
  var selectedVal = $(this).val();
  if(selectedVal == 'bob')
    {
      var html ='<option selected disabled>Select Claim:</option>';
      for(var i=1;i<userClaims.length;++i)
         {
           if(i==1||i==2||i==3)
             {
                html=html+'<option>'+userClaims[i].Type+'</option>';
             } 
          }
      $('#selectAuthPolicy').html(html);
      }
    })
 })

this is just a basic dea of how you can achieve this i just tried for bob there are many other ways to immplement ths

Upvotes: 1

Related Questions