rumi
rumi

Reputation: 3298

how to compare selected dropdownlist value with a model property in MVC

In my MVC app I have a dropdownlist tied to a model like below

class MyObjectViewModel
{
    //comes from WebService, but that doesnt matter here
    List<PersonViewModel> AllPeople= {person1,person2, etc} 
   // PersonViewModel has properties like Id, Name, NeedToInform

    int SelectedPersonId;
}

@model MyModels.MyObjectViewModel

@Html.DropDownListFor(m=> m.SelectedPersonId, 
      Model.AllPeople.Select(p=>new SelectListItem{Value = p.Id, Text=p.Name}), new { @class = "form-control", onchange = "process(this.value)" })

The client side code like like below

<script>
 process (val) {
 console.log(val);        
}         
</script>

I can get the selected value i.e. Id from PersonViewModel but I need to compare if the selected person from PersonViewModel has the property NeedToInform to be true. Not sure how can we do it in the javascript function, something on these lines

   <script>
    process (val) {
    console.log(val);
    //Here I need to compare the model like 
    // var [email protected](x=>x.Id===val).NeedToInform        
  }         
</script>

Upvotes: 1

Views: 111

Answers (1)

Serge
Serge

Reputation: 43860

Try this

<script>

var model = @Html.Raw(Json.Encode(Model));
console.log(JSON.stringify(model));

    process (val) {
    console.log(val);

    let needToInform= null;

model.allPeople.forEach((item) => {
    if (item.Id === val) {
      needToInform = item.NeedToInfom;
     break;
    }
});
        
  }         
</script>

if the model is very large , you can use ajax to send a request to a special api that returns data you need.

Upvotes: 1

Related Questions