【问题标题】:Using Tryparse to convert string to decimal in mvc.net在 mvc.net 中使用 Tryparse 将字符串转换为十进制
【发布时间】:2015-09-04 09:50:03
【问题描述】:

我已经建立了一个连接到 sql 表的 MVC.net 页面,并且我在上面使用了数据表。表列类似于 Customername、mobileNO、Icno、salary、transactiondate。

我设法获得了一些搜索/过滤功能,因此我可以按客户姓名或手机号码进行搜索,但我无法按日期或薪水(十进制)进行搜索。

我的前端搜索字段包括搜索值:输入您的搜索(字符串)和搜索类型:下拉列表:icno、名称、日期。

以下是我的控制器中的代码。如何使其也可以按薪水(小数)和日期进行搜索。

我听说我可以使用 tryparse 但我不知道如何在这里。 Salary 在我的班级中被定义为十进制数据类型,而 transactiondate 作为 DateTime 数据类型。

if (!string.IsNullOrEmpty(fm["SearchValue"]) && !string.IsNullOrEmpty(fm["SearchType"]))
{
     criteria.Add(Restrictions.Like(fm["SearchType"], "%" + fm["SearchValue"] + "%"));                
}
if (!string.IsNullOrEmpty(fm["SearchValue"]) && !string.IsNullOrEmpty(fm["SearchType"]))
{
     criteria.Add(Restrictions.Like(fm["SearchType"], "%" + fm["Icno"] + "%"));
}
if (!string.IsNullOrEmpty(fm["SearchValue"]) && !string.IsNullOrEmpty(fm["SearchType"]))
{
     criteria.Add(Restrictions.Like(fm["SearchType"], "%" + fm["MobileNo"] + "%"));
}

【问题讨论】:

  • 你看过decimal.TryParse的文档了吗?您是否尝试过使用它?
  • 我已经读过它,但我不知道如何在这个特定的场景中应用它,我应该解析什么?我仍然很困惑,对整个 c# 来说是全新的
  • 您阅读文档了吗?你有没有试过用谷歌搜索 TryParse? 因为这个问题没有多大意义——要么你有一个要转换的字符串,要么你实际上是在问如何编写 SQL 查询并生成一个完全不相关的问题。您发布的代码似乎与这两种情况都无关
  • 我有,它看起来像这样 public static bool TryParse(string s, out decimal result)
  • 我只是不确定如何在我这里应用它

标签: c# asp.net-mvc nhibernate


【解决方案1】:

为此,请使用 decimal.parsedecimal.TryParse

var toConvert = "1.5";

var converted = decimal.Parse(toConvert);

如果你在哪里做(在控制台应用程序中):Console.WriteLine(converted); 结果将是 1.5

【讨论】:

    【解决方案2】:

    为什么不使用 Convert.ToDecimal("stringValue")。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2022-07-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-04-09
      • 2016-03-06
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多