Jot Dhaliwal
Jot Dhaliwal

Reputation: 1500

Access MVC model property in Javascript

I have a follwing view page in MVC project

@foreach (var item in Model)
    {
            <tr>
            <td>
                @Html.DisplayFor(modelItem => item.ControlLabel)
            </td>
            <td>
                @Html.DisplayFor(modelItem => item.ControlType)
            </td>
            <td>
                @Html.DisplayFor(modelItem => item.ControlDatatype)
            </td>
            <td>
                @Html.DisplayFor(modelItem => item.MasterModule.ModuleName)
            </td>
            <td>
                @Html.DisplayFor(modelItem => item.Form.FormName)
            </td>
            <td>
                @Html.ActionLink("Edit", "Edit", new { id = item.ControlID }) |
            @Html.ActionLink("Details", "Details", new { id = item.ControlID }) |
            @Html.ActionLink("Delete", "Delete", new { id = item.ControlID })
            </td>
        </tr>
    }

i want to access ControlType in my javascript function, can i do this ? if yes then please guide me

Upvotes: 1

Views: 679

Answers (2)

Caffeine addicted
Caffeine addicted

Reputation: 324

@foreach (var item in Model)
    {

        <tr>
            <td>
                @Html.DisplayFor(modelItem => item.ControlLabel)
            </td>
            <td>
                @Html.DisplayFor(modelItem => item.ControlType)
            </td>
            <td>
                @Html.DisplayFor(modelItem => item.ControlDatatype)
            </td>
            <td>
                @Html.DisplayFor(modelItem => item.MasterModule.ModuleName)
            </td>
            <td>
                @Html.DisplayFor(modelItem => item.Form.FormName)
            </td>
            <td>
                @Html.ActionLink("Edit", "Edit", new { id = item.ControlID }) |
            @Html.ActionLink("Details", "Details", new { id = item.ControlID }) |
            @Html.ActionLink("Delete", "Delete", new { id = item.ControlID })
            </td>
        </tr>

        if (item.ControlType == "blah")
        {
        <script type="text/javascript">

          alert("a");

        </script>

        }
    }

Upvotes: 1

Brian Mains
Brian Mains

Reputation: 50728

Sure, by rendering. You can render anything out in client side javascript like:

<script>
   var controlType = "@(Model[0].ControlType)";
</script>

Or like:

<a href="#" onclick="doSomethingFIrst(@(Model[0].ControlType))">

Something like that; replace 0 with the index in the model's collection that you want. That is fine to do but you have to be careful because you are rendering here, so it has to be something that's usable by client-side javascript (primitive types) or serialized data (using JSON.NET or something like that).

Upvotes: 0

Related Questions