if my view's model is
@model List<myModel>
can I do the following in javascript
<script>
var someint = 0;
var modelValue = @Model[someint].myValue;
</script>
You client side code will not understand @model as it's server side code.
Alternatively you could convert the entire server-side model into a JS object by doing
var model = @Html.Raw(Json.Encode(Model));
Or if you just want the particular property value then just do
var modelValue = @Html.Raw(Json.Encode(Model.myValue));
In case if you Model is a collection then you can use a sequential for loop to iterate over your model collection like
<script type="text/javascript">
var model = @Html.Raw(Json.Encode(Model));
for (var i = 0; i < model.length; i++) {
alert(model[i].myValue);
// Do Something
}
</script>
You can access your model in javascript but you need to quote the razor code
@model List<myModel>
<script>
var modelValue = "@Model[0].myValue"; // add quotes
</script>
however you cannot combine razor and javascript variables so the following does not work (someint is a javascript variable)
<script>
var someint = 0;
var modelValue = "@Model[someint].myValue";
</script>
but the following will
@{ var someint = 0; } // declared in razor
<script>
var modelValue = @Model[someint].myValue;
</script>
you can do something like:
var percent = @Model.TankLevel; //TankLevel is Int within model of model
var cap = @Model.TankCapacity; //TankCapacity is an Int within my model also
percent=(percent/cap).toFixed(2);
As long as
In essence, It's depending on what you're trying to do with the variable modelValue.
Having read your question again, it seems you are trying to almost access the 'list' like an array using an index, which is a definite no no.
You can use this:
var model = @Html.Raw(Json.Serialize(Model));
This method converts the Model object into a JSON string.
or can try for this:
var model = @Html.Raw(Newtonsoft.Json.JsonConvert.SerializeObject(Model))
uses the Json.NET library (Newtonsoft.Json) to convert the Model object into a JSON string.
dataattribute for an input element. You can not directly use the model in JS.someintvariable). This can't be done.