0

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]

Rilcon42
  • 9,584
  • 18
  • 83
  • 167

1 Answers1

1

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

RAHUL S R
  • 1,569
  • 1
  • 11
  • 20
  • I tried this, but was having issues on the `Json.Encode`.... error: `IJsonHelper does not contain a definition for 'Encode'` Did you get this error? – Rilcon42 Apr 04 '18 at 22:29
  • it should not show you that anyway add @using System.Web.Helpers; in top of your view – RAHUL S R Apr 05 '18 at 05:23
  • @Rilcon42 For anyone reading this recently, try `Json.Serialize()` as that's the equivalent to `Json.Encode()` in ASP .NET Core. – Djordje Nikolic Aug 26 '22 at 12:23