Home > Software design >  how to get model values in javascript
how to get model values in javascript

Time:11-03

testModel

public class testModel
{
  public int ID{get; set;}
  public string name{get; set;}
}

cshtml code

@model IEnumerable<testModel>
var lstModel = Model.ToList();
<div id="mainOfferDiv">
@for(int i = 0; i<lstModel.Count(); i  )
{
}
</div

In js file i want to get list of testModel data which is there in cshtml file, I tried with below

js file

var listModel = document.getElementById("mainOfferDiv");

Suppose lstModel contains list of 10data i want to get same in js file

Thank you in advance

CodePudding user response:

You could take your entire server-side model and turn it into a Javascript object by doing the following:

var model = @Html.Raw(Json.Encode(Model));

In your case if you just want the FloorPlanSettings object, simply pass the Encode method that property:

var floorplanSettings = @Html.Raw(Json.Encode(Model.FloorPlanSettings));

another way is

Classs property ---
        Name = "Raj",
        IsAuthenticated = true,
        LoginDateTime = DateTime.Now,
        Age = 26,
        UserIconHTML = "<i class='fa fa-users'></i>" 
---------------------------------

js in cshtml

var Name = @Model.Name;  
var Age = @Model.Age;
var LoginTime = @Model.LoginDateTime; 
var IsAuthenticated = @Model.IsAuthenticated;   
var IconHtml = @Model.UserIconHTML; 
  • Related