Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to access Model.Something value in ASP MVC at View's javascript section

Tags:

asp.net-mvc

I would like to access a Model property value in ASP MVC at the View's javascript section

What is the best way to do so?

Thanks

like image 663
Ws. Avatar asked Oct 24 '09 16:10

Ws.


People also ask

How do I access model value in view?

In Solution Explorer, right-click the Controllers folder and then click Add, then Controller. In the Add Scaffold dialog box, click MVC 5 Controller with views, using Entity Framework, and then click Add. Select Movie (MvcMovie. Models) for the Model class.

How do you transfer data from model to view?

The other way of passing the data from Controller to View can be by passing an object of the model class to the View. Erase the code of ViewData and pass the object of model class in return view. Import the binding object of model class at the top of Index View and access the properties by @Model.

Can we use model in JavaScript?

With the object model, JavaScript gets all the power it needs to create dynamic HTML: JavaScript can change all the HTML elements in the page. JavaScript can change all the HTML attributes in the page.

How do you use a model in razor view?

Right-click in the Store Index action method and select Add View as before, select Genre as the Model class, and press the Add button. This tells the Razor view engine that it will be working with a model object that can hold several Genre objects.


2 Answers

I can't think of another way then just simpy printing it ;

<script type="text/javascript">
    var myJavaScripVar = '<%=Model.Property %>';
</script>
like image 66
Çağdaş Tekin Avatar answered Oct 21 '22 07:10

Çağdaş Tekin


Another option is to use an Ajax request to a controller method that returns a json result.

like image 41
Matthew Avatar answered Oct 21 '22 05:10

Matthew