I have to get values from a controller method in a view to write into some javascript. In web pages it is as simple as <%=functionName()%>. Is there a way to do this in MVC. I cannot use the model because the javascript has to be available on page load. Any insights appreciated.
I have to get values from a controller method in a view to write into some javascript. In web pages it is as simple as <%=functionName()%>. Is there a way to do this in MVC. I cannot use the model because the javascript has to be available on page load. Any insights appreciated.
Share Improve this question asked Aug 15, 2012 at 14:17 user1069733user1069733 4859 silver badges17 bronze badges1 Answer
Reset to default 8Is there a way to do this in MVC
Yes, of course.
I cannot use the model because the javascript has to be available on page load.
Of course that you can use a view model, there's nothing that would prevent you from doing so. So you start by defining it:
public class MyViewModel
{
public string Foo { get; set; }
}
then have a controller action that will populate this view model and pass it the view:
public ActionResult Index()
{
var model = new MyViewModel();
model.Foo = "Hello World";
return View(model);
}
and finally have a strongly typed view to this view model in which:
@model MyViewModel
<script type="text/javascript">
$(function() {
var foo = @Html.Raw(Json.Encode(Model.Foo));
alert(foo);
});
</script>
But now let's suppose that you don't want to pollute your view with javascript but have it in a separate js file instead (which of course is the correct way).
You could embed the value somewhere in your DOM, for example using HTML5 data-*
attributes:
<div id="foo" data-model="@Html.Raw(Html.AttributeEncode(Json.Encode(Model)))">
Click me to surprise you
</div>
and then in a separate javascript subscribe to the click event of this element and read the data-*
attribute in which we have JSON serialized the entire view model:
$(function() {
$('#foo').click(function() {
var model = $(this).data('model');
alert(model.Foo);
});
});