简体   繁体   English

从Razor传递变量到Javascript

[英]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. 我认为这需要通过Javascript完成,并确定要显示哪个窗口,我需要将ID参数(对象的属性之一)传递给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? 有人知道哪里出了问题吗?

This: 这个:

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

...will put the string "theId" in the attribute. ...会将字符串“ theId”放入属性。 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. @将让剃刀模板引擎知道切换到输出.NET值。

尝试

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM