Access a Model Property via JS when it's a ViewModel

I have a ViewModel composed of 3 models. I also have a jquery script where I make a reference to a property, but this property appears in more than 1 model.

<script type="text/javascript">
    $document.ready(function () {
        var items = "<option value='0'>Select</option>";
        $('#DistrictID').html(items);
    });
</script>

How can I reference that DistrictID belongs to a specific model?

like -

$('#SpecificModel.DistrictID').html(items);

Upvotes: 0

Views: 396

Answers (1)

Willy David Jr
Willy David Jr

Reputation: 9171

I am not sure what you really want to accomplish, but based on your question, you want to get the value on the property you have on your Model with 3 Models inside:

Try this on your Javascript section:

   <script type="text/javascript">
     $document.ready(function () {
     var items = "<option value='0'>Select</option>";
     var itemWithViewProperty = @Html.Raw(Json.Encode(Model.SpecificModel.DistrictID));

     //Now you can use this variable 'itemWithViewProperty' and prints its value like:
     Console.Log(itemWithViewProperty);
     //But accessing it like  $('#DistrictID').html(items); will not work since its an element ID you are passing here and not a variable value
});

Make sure to specify the specific model after the Model word.

Upvotes: 2

Related Questions