NicTam
NicTam

Reputation: 51

Passing Variable from Razor to Javascript

So I have a list of objects in my controller, and I would like to have a button that initiates a pop-up window, which associates with each of the object in the list. I think this needs to be done by Javascript, and to identify what window to display, I would need to pass the ID parameter (one of the attributes of the object) to the javascript. I currently have the following code:

@Html.BeginForm()
{
            @for (int i = 0; i < Model.Count(); i++)
            {
                var theId = Model[i].CW_Id;
            <tr>
                <td>
                    <input type="button" id="btnpopup" value="Details" onclick="ShowModelPopUp()" data="theId" />
                </td>
                @Html.EditorFor(m => Model[i], "CWinline") //Compiles the list using Editor Template
            </tr>
            }
            </table>

        <input type="submit" value="Save" class="btn btn-default" />
    }

    <script type="text/javascript">
        ShowModelPopUp = function () {
            var theId = $(this).data();
            window.showModalDialog('/Default/Selected/?id='+theId, "WindowPopup", 'width=200,height=500');
        }

    </script>

Somehow the variables aren't passing properly. Does anyone know where it went wrong?

Upvotes: 0

Views: 841

Answers (2)

Jonathan Felipe
Jonathan Felipe

Reputation: 1

try

 <input type="button" id="btnpopup" value="Details" onclick="ShowModelPopUp()" data="@Model.id_attribute" />

Upvotes: 0

Jacob
Jacob

Reputation: 78920

This:

<input 
  type="button" id="btnpopup" 
  value="Details" 
  onclick="ShowModelPopUp()" 
  data="theId" />

...will put the string "theId" in the attribute. You want this:

<input 
  type="button" id="btnpopup" 
  value="Details" 
  onclick="ShowModelPopUp()" 
  data="@theId" />

The @ will let the razor template engine know to switch to output a .NET value.

Upvotes: 1

Related Questions