【问题标题】:How to get a value of <#= Id #> when passed to a helper method传递给辅助方法时如何获取 <#= Id #> 的值
【发布时间】:2012-02-02 10:00:16
【问题描述】:

我正在使用ASP.NET MVC 3 和razor。我也在用最新版的Telerik MVC。

我的视图上有一个显示应用程序列表的网格。每个应用程序都有一个状态。我需要编写一个辅助方法来根据每个应用程序的当前状态在网格的每一行中显示链接。如果状态为 1,那么我需要显示一个编辑链接。我的助手看起来像这样:

public static string ActionLinks(this HtmlHelper helper, string grantApplicationId, string grantApplicationStateId)
{
     List<TagBuilder> linkList = new List<TagBuilder>();
     string actionLinks = string.Empty;

     if (grantApplicationStateId == "1")
     {
          // Edit link
          TagBuilder editLink = new TagBuilder("a");
          editLink.MergeAttribute("href", "/GrantApplication/Edit/" + grantApplicationId);
          editLink.InnerHtml = "Edit";
          linkList.Add(editLink);
     }

     foreach (TagBuilder link in linkList)
     {
          actionLinks += link.ToString() + "<br>";
     }

     return actionLinks;
}

我的 Telerik 网格中的网格列如下所示:

column.Bound(x => x.Id)
     .ClientTemplate(@Html.ActionLinks("<#= Id #>", "<#= GrantApplicationStateType.Id #>"))
     .Title("Actions");

我的视图模型如下所示:

public class GrantApplicationListViewModel
{
     // Just partial properties
     public GrantApplicationStateType GrantApplicationStateType { get; set; }
}

GrantApplicationStateType 看起来像:

public class GrantApplicationStateType : IEntity
{
     public int Id { get; set; }
     public string Name { get; set; }
}

当调用上述辅助方法时,grantApplicationStateId 的值为“”。我将如何获得通过的值?我的意思是,如果传递的值为 1,我将如何获得 1,因为目前它是“”?

2012-02-06 更新

我尝试了 Darin 的链接,在我的代码中使用了完全相同的示例,但更改了以下内容:

column.ActionLink("Open", "Edit", "GrantApplication", item => new { id = item.Id, applicationStateId = item.GrantApplicationStateType.Id });

我需要传递 2 个值。我需要对授权应用程序状态 ID 执行几个 if 语句,然后将特定操作链接返回给客户端。但是在遍历以下值时失败:

if (memberExpression.Expression is ParameterExpression)
     value = string.Format("<#= {0} #>", memberExpression.Member.Name);
else
     value = GetValue(memberExpression);

传入的第一个参数通过if语句的第一/真部分:

value = string.Format("<#= {0} #>", memberExpression.Member.Name);

..但是第二个参数通过 if 的 false 部分:

value = GetValue(memberExpression);

两者有什么区别?

然后它在 GetValue 方法中失败并显示以下消息:

variable 'item' of type MyProject.ViewModels.GrantApplicationListViewModel' referenced from scope '', but it is not defined

我无法让它工作,我又寻找了一些样本但找不到任何样本。

【问题讨论】:

  • 你的模型是什么样子的

标签: asp.net-mvc asp.net-mvc-3 telerik telerik-grid telerik-mvc


【解决方案1】:

你不能使用助手来做到这一点。在 ASP.NET MVC 中,帮助程序在服务器上运行。注意到 Telerik 网格中的 ClientTemplate 名称了吗?这意味着在客户端上运行。

它的作用是它只是使用&lt;#= Id #&gt; 作为服务器端助手的占位符,该助手将生成一些 HTML 和 在客户端,Telerik 网格将在为了放置只有客户端知道的值。

在您的服务器端 ActionLinks 助手被调用的那一刻,Telerik 网格无法将仅在客户端知道的实际值传递给您。

您可以查看following blog post 以获得不错的扩展。

【讨论】:

  • 它似乎可以工作,我只需要修改它以适应我的场景。
猜你喜欢
  • 2012-12-28
  • 1970-01-01
  • 2012-08-07
  • 2019-05-05
  • 2022-11-30
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多