Use Class Library C# variables in a .cshtml <script type="text/javascript"></script>

Viewed 171

I'm trying to access some C# variables from my js script. I have a .NET project in VisualStudio, and another WebApp project (MVC template).

I want to access some of the data from my Class Library, in my .cshtml, in the part at the bottom of my script where I've added a <script type="text/javascript"></script> block.

Is this possible?

I've added the .NET project as a Reference for the WebApp, so I can technically access it somehow, but not sure how to pass it or if to use the Controller View() to do this or some other way...

Thanks

1 Answers

I don't know how your current structure is like, so I will be assuming you have a class in our C# DLL e.g.

public class Foo 
{
   public string SomeVariableInOurDll => "Test"; //this can be of whatever type
}

Now moving to your MVC project. Let's create a view model:

public class SomeViewModel
{
    public string VariableToReadInJs { get; set; }
}

Inside your controller action you can now do:

public class HomeController : Controller
{
    public ActionResult Index()
    {
        var foo = new Foo();

        var model = new SomeViewModel
        {
            VariableToReadInJs = foo.SomeVariableInOurDll
        };

        return View(model);
    }
}

Finally inside your view your js code will be something like:

<script>
     var myVal = '@Model.VariableToReadInJs';
     ...
</script>

Finally, at the top of your .cshtml ensure you use the view model as:

@model SomeViewModel
Related