Raj Singh
Raj Singh

Reputation: 163

How to access c# model data in javascript

New to ASP.NET MVC 3. Started with a tutorial and am mirroring the code for my own model. I Can access the model data in my Index.cshtml file in the script but not in my javascript functions.

My Model

using System.ComponentModel.DataAnnotations;

namespace DotNetCoreSqlDb.Models

{
    public class Glassblower
    {
        public int ID { get; set; }
        public string TeacherID { get; set; }
        public string Lat { get; set; }
        public string Lng { get; set; }
        public string Name { get; set; }
        public string Bio { get; set; }
        public string Url { get; set; }
        public string Coe { get; set; }
        public string SubscriptionLevel { get; set; }
        public DateTime StartDate { get; set; }

    }
}

My controller Index method:

// GET: Glassblowers
        public async Task<IActionResult> Index()
        {
            return View(await _context.Glassblower.ToListAsync());
        }

My Index.cshtml

@model IEnumerable<DotNetCoreSqlDb.Models.Glassblower>

@{
    ViewData["Title"] = "Index";
}

<script id="gmapsrc" src="https://maps.googleapis.com/maps/api/js?key=AIzaSyBSJAns0GMR5gK60kw2c3IAnouZpyu_QHw"
></script>



<div class="row map-and-readout-container">
     <div id="timescale-map" class="timescale-map"></div>
    <div id="readout" class="readout">

       @foreach (var item in Model) {
               <div>
                @Html.DisplayFor(modelItem => item.Name)
               </div>
        }
    </div>

</div>
<script>
 var model = @Html.Raw(Json.Encode(@Model));
</script>

Currently I am able to render the item names on the page. My goal is to loop through the model in a javascript function in my tag.

I've tried accessing it with

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

but when I click run in Visual Studio Mac I get this build error

'IJsonHelper' does not contain a definition for 'Encode' and no accessible extension method 'Encode' accepting a first argument of type 'IJsonHelper' could be found (are you missing a using directive or an assembly reference?) (CS1061) (DotNetCoreSqlDb)

Any Tips would be greatly appreciated. Thanks

Upvotes: 0

Views: 1033

Answers (1)

Dannick Bedard
Dannick Bedard

Reputation: 402

It's beacause your models is not json, you can try to put it in a array or list like this.

<script>
    var availableTags = [];
    @foreach(var model in Model.Model)
    {
        @:availableTags.push(decodeHtml("@model"));
    }
</script>

Upvotes: 1

Related Questions