Ranjith Varatharajan
Ranjith Varatharajan

Reputation: 1694

Use View model in Javascript

Scenario:

A partial view has a model, I need to use the value from the model in the javascript which is in seperate .js file.

Currently, I'm using javascript inline so that the value in the model can be used, but what if, the javascript is moved to a seperate file. In this case how do I get those values.

Code

@model IEnumerable<BookSpec.DomainEntities.ContactModel.ContactDataModel>
<label for="SpecFinder">Contact</label>
<select id="SpecFinder" name="state">
@foreach (var name in Model)
{
    <option value="@name.GroupID">@name.GroupName</option>
}
</select>

<script type="text/javascript">
    $(document).ready(function () {
        $("#SpecFinder").change(function(){
            getData(this.value,'@Model.ProductID');
        });
    })
</script>

This is my current example code looks like, and I want to completely move the inline javascript to a seperate file. How can I do it, I also need the values from the model.

Upvotes: 1

Views: 2392

Answers (2)

piraces
piraces

Reputation: 1348

I think @Karan response is a good option. But if you want no inline Javascript, you could assign your model to a hidden HTML input and then retrive the value in whatever other external JS file you want.

With something like Html.Hidden, for example:

@Html.Hidden("myModel", new Microsoft.Web.Mvc.MvcSerializer().Serialize(model, SerializationMode.Signed));

You can choose another serialization mode in the SerializationMode enum.

(Code not tried, but should be close)

Upvotes: 0

Karan
Karan

Reputation: 12629

Declare global javascript variable model on view as below. Then you can use it anywhere.

<script type="text/javascript">
    var model = @Html.Raw(Json.Encode(Model));
</script>

I will recommend to use above solution. But if you still want to not include any script in partial view then you can render the model inside any hidden div. And access its text and convert it to object using JSON.parse as below. Code like below is not a good practice and like patch work.

HTML

<div id="model" style="display:none;">
    @Html.Raw(Json.Encode(Model))
</div>

Script

var model = JSON.parse($("#model").text());

Upvotes: 2

Related Questions