How can I get the value of the first item from the model's List? My ViewModel:
namespace TestWeb
{
public class NavViewModel
{
public NavViewModel()
{
NavStepList = new List<NavStep>();
}
public List<NavStep> NavStepList { get; set; }
}
}
In my View:
@using TestWeb
@model NavViewModel
<script>
$(document).ready(function () {
var Testvalue = @Model.NavStepList.First();
});
</script>
I want the first value of NavStepList
. However an error occurs when I call this function:
TestWeb is undefined
I already test with testing value assign to NavStepList
but the error still occurs.
My NavStep Class Property:
public class NavStep{
public int NavStepId { get; set; }
public int SortId { get; set; }
public string StepName { get; set; }
public string IdentifierKey { get; set; }
public bool IsAvailible { get; set; }
}
3 Answers 3
You could convert your server side view model to a javascript variable using the following:
<script>
$(document).ready(function () {
var myModel = @Html.Raw(Json.Encode(Model.NavStepList.First()));
});
</script>
and then you could access your model properties in javascript:
alert(myModel.NavStepId);
alert(myModel.SortId);
alert(myModel.StepName);
...
Comments
Here @Model ought to refer to NavViewModel directly. Also, as Rory said, trying to assign a class, NavStep to a javascript variable isn't going to work out. What you probably want is:
var navStepId = @Model.First().NavStepId;
var sortId = @Model.First().SortId;
var stepName = "@Model.First().StepName"; //wrap strings in "" so javascript recognizes them as such
var identifierKey = "@Model.First().IdentifierKey";
var isAvailable = "@(Model.First().IsAvailable)" === '@true'; //method to convert c# true to javascript true
6 Comments
Case
The @NavViewModel
model exists on server.
jQuery
script are running on client (browser)
Problem
How to access server side object on client?
Solution : Serialize sever side object to client
As we can not directly access server-side objects on client We need to serialize the model (full/part).
var flatmodel = [@Html.Raw(Json.Encode(Model.NavStepList.First()))][0];
Now flatmodel is JavaScript variable and we can access property via flatmodel
.
NavStep
class to give you a definitive answer.