ViewData 显示数据库列名

ViewData displaying database column name

我尝试将一些数据输入到名为 "Cost" 的 ViewData 中。这是从数据库中的 "PrinterCreditsCost" 列中获取一个值,并且应该显示该列的值。但是,列名也显示有大括号,因此与仅显示“2”相反,它显示“{ PrinterCreditCost = 2 }”。有谁知道我怎样才能让它只显示“2”。这将用于数学方程式,所以我只需要 2.

代码如下:

var result = (from a in db.tblOptions.Include(t => t.PrinterCreditCost)
where a.ID == 1
select new
{
    a.PrinterCreditCost
}
).First();
ViewData["Cost"] = result;

Jason 更新:

        public int ID { get; set; }
    public int Visible { get; set; }
    public int DeleteLicense { get; set; }
    public Nullable<int> ICTSurvey { get; set; }
    public Nullable<int> PaidWorkSurvey { get; set; }
    public Nullable<int> ICTGeneralSurvey { get; set; }
    public Nullable<int> PESSCLSurvey { get; set; }
    public Nullable<int> PastSurvey { get; set; }
    public Nullable<int> PresentSurvey { get; set; }
    public Nullable<int> Yr11Survey { get; set; }
    public Nullable<int> NewScientistCount { get; set; }
    public Nullable<int> UCASYear { get; set; }
    public Nullable<int> OnlineSurveyActive { get; set; }
    public Nullable<int> OnlineExaminationsActive { get; set; }
    public string UCASFirstHalf { get; set; }
    public string UCASSecondHalf { get; set; }
    public string SIMSManual { get; set; }
    public string SIMSApplication { get; set; }
    public string SIMSAmpark { get; set; }
    public Nullable<double> PrinterCreditFund { get; set; }
    public Nullable<int> PrinterCreditCost { get; set; }
    public string UCASIndividualFirstHalf { get; set; }
    public string UCASIndividualSecondHalf { get; set; }
    public string BookingSheetYear { get; set; }
    public Nullable<System.DateTime> InductionDate { get; set; }
    public string InductionYear { get; set; }

    public virtual ICollection<tblPrinterCredit> tblPrinterCredits { get; set; }

一种可能的方法是将结果存储在一个字符串和该存储字符串的 select 子字符串中,并将其分配给视图数据。

  string abc = result;
  string viewdatastring = abc.substring(20);
  ViewData[Cost]= viewdatastring

只需在这里查看有关子字符串的教程

http://www.dotnetperls.com/substring

在这部分查询中

select new
{
    a.PrinterCreditCost
}

是否有 PrinterCreditCost 中的 属性 需要使用,例如

select new
{
    a.PrinterCreditCost.Value
}

我不知道 Value 是否是您需要的 属性,它可能被称为其他名称。

就目前而言,您的查询确实是 return列定义,而不是该列的值。

编辑:

我看到以下内容:

public Nullable<int> PrinterCreditCost { get; set; }

所以我很惊讶

select new
{
    a.PrinterCreditCost.Value
}

无效。因为它是一个可以为 null 的值,所以 .Value 属性 应该 return 值,而不是 { Value = 2 }。我不确定那里发生了什么。

var result = (from a in db.tblOptions.Include(t => t.PrinterCreditCost)
where a.ID == 1
select new
{
    a.PrinterCreditCost
}
).First();
ViewData["Cost"] = result;

不正确,但是,将其更改为:

    var result = (from a in db.tblOptions.Include(t => t.PrinterCreditCost)
where a.ID == 1
select new
{
    a.PrinterCreditCost
}
).First();
ViewData["Cost"] = result.Value;

(添加 .Value)到 ViewData 行的末尾即可。