最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

asp.net mvc - MVC Razor get values from controller in a view for javascript - Stack Overflow

programmeradmin6浏览0评论

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 badges
Add a ment  | 

1 Answer 1

Reset to default 8

Is 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);
    });
});
发布评论

评论列表(0)

  1. 暂无评论