【问题标题】:Creating method using C# in ASP.NET with Razor syntax在带有 Razor 语法的 ASP.NET 中使用 C# 创建方法
【发布时间】:2014-07-25 01:16:59
【问题描述】:

问题已解决:我找到了可重复使用的解决方案。谢谢大家的帮助。

我很沮丧,不知道自己在做什么。我正在尝试构建一个网页,而我正在尝试做的一件事就是减少代码。为此,我需要创建一个方法,我对 Java 中的方法有广泛的了解,但在尝试使用剃刀语法在 ASP.NET 中编写 C# 时却不是这样。我面临的问题是我的@helper 拒绝访问全局哈希表“字典”。我尝试了很多不同的方法,并决定求助于 stackoverflow。提前致谢。

更新:

错误消息是“CS0103:当前上下文中不存在名称‘字典’”

我需要一个哈希表,因为我从数据库中提取,检查它是否为空,如果是,则将其替换为空字符串,然后将其推送到表中。因此,如果我能以这种方式学习如何做到这一点,我认为效果最好?

<!doctype html>

@using System;
@using System.Collections.Generic;
@using System.Collections;
@using System.Linq;

@{
    var dictionary = new Dictionary<string, object>();

    dictionary.Add("fName", returnString100.FRSTNAME.Trim());

    @helper printOut(string toBePrinted) {
        object curValue;
        if(dictionary.TryGetValue(toBePrinted, out curValue)) { 
            return curValue; 
        }
    }
}

<table>
    <tr>
        <td>First Name:</td><td>@{ printOut("fName"); }</td>
    </tr>
</table>

【问题讨论】:

  • 听起来这个逻辑不属于您的视图或助手。为什么不在 helper 方法中声明你的字典呢?
  • 这看起来对于一个视图来说代码太多了。这应该真正属于模型,并且视图只会引用该模型的属性。
  • 请发布您从此代码中得到的错误。
  • 错误信息是“CS0103:当前上下文中不存在名称‘字典’”

标签: c# asp.net razor


【解决方案1】:

虽然我同意其他人的观点,即您可能希望将其封装在一个类中,但以下是在 Razor 中使用视图执行此操作的方法:

<!doctype html>

@using System;
@using System.Collections.Generic;
@using System.Collections;
@using System.Linq;

@{
    var dictionary = new Dictionary<string, object>();

    dictionary.Add("fName", returnString100.FRSTNAME.Trim());

    Func<string, object> PrintOut = delegate(string toBePrinted)
    {
        object curValue;
        if (dictionary.TryGetValue(toBePrinted, out curValue))
            return curValue;
        return "";   
    };

}

<table>
    <tr>
        <td>First Name:</td><td>@PrintOut("fName").ToString()</td>
    </tr>
</table>

【讨论】:

  • 但是我不知道你从哪里得到 returnString100。我将把它留给你,因为这不是问题的一部分:)
  • 是否可以跳过所有这些,直接从我的哈希表中提取。示例 dictionary.TryGetValue("fName").ToString() ?
  • 另外我看不出答案如何让我重用代码,因为没有涉及参数。我正在提取一个名称,因为它是每个用户的显示,因此需要将其用于多个字段
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2011-10-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-02-15
  • 1970-01-01
  • 2011-08-18
相关资源
最近更新 更多