1

I have an ASP.NET MVC project and I am trying to access a model property (isNew) from the view (.cshtml) and from within javascript function so I am performing below without success:

@model My.Common.DTOs.MyDTO

function Initizalize()
{
   if (!@Model.isNew)
   {
      DoSomeStuff(); // call another javascript function
   }   
}

function DoSomeStuff()
{
}
Willy
  • 9,848
  • 22
  • 141
  • 284

3 Answers3

1

You can achieve it by this way

if (!@Model.isNew)
{
  <script>
   DoSomeStuff(); // call another javascript function
  </script>
}  
Nguyễn Văn Phong
  • 13,506
  • 17
  • 39
  • 56
0

You can try this at your scripts section.

@section scripts{
  <script>
      var isNew = @Html.Raw(Json.Encode(Model.isNew));

      function Initizalize()
      {
          if (!isNew)
          {
              DoSomeStuff();
          }   
      }

      function DoSomeStuff() {

      }

      Initizalize();

  </script>
}
Hasanuzzaman
  • 1,822
  • 5
  • 36
  • 54
-1

Is this question related to your problem? There's a pretty in-depth answer on how to access model data in Javascript/Jquery code block in a .cshtml file. Best of luck.

CinnamonRii
  • 156
  • 1
  • 10