Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I use Razor values in a javascript function? [duplicate]

Possible Duplicate:
using razor within javascript

I would like to place a siimple value from the model on a razor page and use it as a constant value in a javascript function. i.e.

<script> var myValue = @Model.myRecord.Count();</script>

so that myValue = the record count in my model. I am using myRecord.Count as an example, it could be any value from my model.

Is this possible?

TIA J

OK I stumbled across the following solution:

<script> var myValue = @(Model.myRecord.Count())</script>

Just putting inthe extra brackets helped.

like image 217
John S Avatar asked Sep 10 '12 20:09

John S


People also ask

Can you use Razor syntax in JavaScript?

You can't. Razor is a . NET assembly and doesn't run on JavaScript or in a browser. It's meant to be executed server-side.

Can I use JavaScript in Blazor?

A Blazor app can invoke JavaScript (JS) functions from . NET methods and . NET methods from JS functions. These scenarios are called JavaScript interoperability (JS interop).

How do Razor Pages work?

Razor Pages focus on page-based scenarios for building web applications rather than using controllers and views like a traditional ASP.NET MVC application. Once the application receives an HTTP request, it moves through the middleware pipeline until it reaches a middleware component that can handle and process it.

What is razorpage?

What are Razor Pages? Razor pages are simple and introduce a page-focused framework that is used to create cross-platform, data-driven, server-side web pages with clean separation of concerns.


1 Answers

Sure, just make sure to properly encode it. For example you could JSON encode the entire model itself:

@model IEnumerable<MyViewModel>
<script type="text/javascript">
    var model = @Html.Raw(Json.Encode(Model));
    // at this stage the model javascript variable represents the JSON encoded
    // value of your server side model so that you can access all it's properties:
    alert(model.length);
</script>

or:

alert(model[2].Foo.Bar);

or whatever.

But if you only care about the number of elements inside the model (if this model represents a collection):

var count = @Html.Raw(Json.Encode(Model.Count()));
alert(count);
like image 142
Darin Dimitrov Avatar answered Sep 19 '22 20:09

Darin Dimitrov