【问题标题】:Building a string that starts with a number and the second part of the string is to have a common indent构建一个以数字开头的字符串,字符串的第二部分是有一个共同的缩进
【发布时间】:2013-09-14 00:40:22
【问题描述】:

我正在构建一个值以显示在下拉选择框中。该值由货币值和用户名组成。我想要的是用户名都以相同的缩进开头。

Ex(我目前拥有的):

$1,000  UserA
$100  UserB
$10  UserC

我想要什么:

$1,000  UserA
$100    UserB
$10     UserC

甚至更好:

$1,000  UserA
  $100  UserB
   $10  UserC

我认为第三个列表是最易读的。

有没有一种简单的方法可以做到这一点,而无需编写检查最大长度的函数,然后手动对其进行格式化或“作弊”来完成此操作?

编辑:我如何生成 ViewModel 项(我传递给我的网页的内容)

    public ActionResult SearchCollections()
    {
        SearchCollectionGridViewModel scgvm = new SearchCollectionGridViewModel();

        var UserNamesWithValues = (from ud in db.userdetails  //build the dataset to pass to the View
                                   join usr in db.my_aspnet_users on ud.IdUsers equals usr.id                                       
                                   select new { 
                                       UserName = usr.name, 
                                       TradeCollectionValue = ud.TradeCollectionValue,
                                       NumberOfTrades = ud.NumberOfTrades,
                                       DollarValueTraded = ud.TradeValue
                                        }).ToList();

        scgvm.TradeCollectionValues = (from c in UserNamesWithValues
                                       where c.TradeCollectionValue > 0
                                       orderby c.TradeCollectionValue descending
                                       select new SelectListItem
                                       {
                                           Text = String.Format("{0,5} {1}", c.TradeCollectionValue, c.UserName).Replace(" ", "\xA0"),
                                           Value = c.UserName
                                       }).ToList();

         return View(scgvm);
     }

编辑 #2:找到/想出答案

我使用下面的答案加上以下两个链接在选择框中生成了一个准确的字符串:(等宽字体也是一个键)

Answer 1

Answer 2

【问题讨论】:

  • 通常我们必须插入一些tab 字符,但是这只有在我们使用fixed-size 字体时才有效。
  • @KingKing 因为这是一个 Web 应用程序,我不确定我能否完全控制该要求。
  • 你在使用网络表单控件吗?
  • @DanielA.White 这是 MVC 4,所以它是我通过视图模型填充的 Razor 辅助函数,例如:@Html.DropDownListFor(x => x.DollarValueTraded, Model.DollarValueTraded, "Dollar Value Traded...", new { @class = "DropDownLists"})
  • 您可以考虑使用其他控件,例如 select2。

标签: html asp.net-mvc razor


【解决方案1】:
String.Format("{0,5} {1}", money, username)

或者,HTML 编码,

Replace(String.Format("{0,5} {1}", money, username), " ", " ")

所以在 MVC4 中它看起来“有点像”:

@Html.Raw(
    Replace(
        String.Format(
            "{0,5} {1}",
            money,
            HttpServerUtility.HtmlEncode(username)
        ),
        " ",
        " "
    )
)

(确保将字体设置为等宽)

【讨论】:

  • 在控制器(服务器端)上构建字符串时如何生成这样的格式。请参阅上面的编辑。
  • 在其他几个 SO 答案的帮助下弄清楚了,感谢您的帮助:)
【解决方案2】:

为什么不使用\t 的标签?

【讨论】:

  • 查看我对 KingKing 的回答
猜你喜欢
  • 2013-05-21
  • 1970-01-01
  • 1970-01-01
  • 2021-04-01
  • 1970-01-01
  • 2015-08-22
  • 1970-01-01
  • 2019-09-17
  • 2021-01-31
相关资源
最近更新 更多