1

I'm using asp.net mvc 3-4.0 and the question is how to pass a model value to a .js file. Sometimes i don't want to put too many jquery lines on my razor view page.

something likes

 $("#qcontent").load(
                    "@Url.Action("QuestionList", "TuongTac")",
                {
                    id: 1,
                    keywords: @Model.keyword
                    ....
                }

is it possible to make it work in a .js file ?

Thanks.

1 Answer 1

2

The cleanest way I've found to do this is to use data-* attributes.

In you Razor view:

<div id="qcontent" data-url="@Url.Action("QuestionList", "TuongTac")" data-keyword="@Model.keyword"></div>

Then in your external JavaScript file:

$("#qcontent").each(function() {
    var url = $(this).data('url');
    var keyword = $(this).data('keyword');
    // ... 
});

Another option is to put the procedural JavaScript in an external file, and then dump out just the settings required in one hit in your Razor view:

<script type="text/javascript">
    var qcontent.settings = @Json.Encode(new { url = Url.Action("QuestionList", "TuongTac"), keyword = @Model.Keyword });
</script>

and refer to it in your JavaScript file:

$("#qcontent").load(qcontent.settings.url, { id: 1, keyword: qcontent.settings.keyword });

The downside of this approach is that you are polluting the global namespace, so you'll want to be careful about namespacing.

Sign up to request clarification or add additional context in comments.

2 Comments

To separate markup from your javascript data and simplify future refactorings it's better to use second option
Agreed, but there are certain situations where the second approach can get a lot more complicated (e.g. in custom editor or display templates which are used more than once per view)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.