首页 > 解决方案 > 如何在 MVC Razor 中动态设置 <% = %>

问题描述

我需要在我的剃须刀代码中动态添加一个关键字段名称。

我只是不确定如何正确设置它,所以 data.KeyNameField 是在运行时设置的

我在剃须刀中尝试了 string.format,但我认为它不会起作用,因为 <% %> 对于在客户端上设置键字段很重要

                                    .CellTemplate(
                                            @<text>
                                            <a href="@Html.Raw(url)?id=<%= data.THE_GUID%>">@Model.OpenRecord.OpenRecordButtonText</a>
                                            </text>);
                                        }

为了能够动态地传递我的关键字段名称,我可以将唯一 ID 添加到我的 URL 中。

我需要用我的键字段名称模型上的属性替换 .'THE_GUID'

标签: razormodel-view-controller

解决方案


回答:

            if (Model.HasOpenRecordButton && Model.OpenRecord != null)
            {
                string urlAction = Url.Action(Model.OpenRecord.OpenRecordButtonAction, Model.OpenRecord.OpenRecordButtonController);

                string rawUrl = string.Format("{0}?id=<%= data.{1} %>", urlAction, Model.KeyFieldName);

                column
                    .Add()
                    .VisibleIndex(Model.OpenRecord.ColumnPositionIndex)
                    .Caption(Model.OpenRecord.Caption)
                    .DataType(GridColumnDataType.String)
                    .Width(Model.OpenRecord.ColumnWidth)
                    .CellTemplate(
                            @<text>
                                <a href="@Html.Raw(rawUrl)">@Model.OpenRecord.OpenRecordButtonText</a>
                            </text>
                    );
            }

其中 data.{1} 将是关键字段名称,并将将该字段的值绑定为 id=*


推荐阅读