if语句在数据库MVC 4中显示1或2

时间:2014-11-13 17:22:31

标签: c# asp.net-mvc asp.net-mvc-4 if-statement

我似乎无法计算出在数据库中显示为1或2的逻辑,具体取决于是否有任何数据。

代码是这样的:

在模型中,逻辑是:

[Display(Name = "Mono Reading:")]
public double? MonoReading { get; set; }

[Display(Name = "Colour Reading:")]
public double? ColourReading { get; set; }

public ReadingsEntry(string serialNumber) : this()
{
    //
    MonoReading = ca.vw_ReadingsEntry.Where(s => s.ser_num == SerialNumber && s.meter_type == "Mono").Select(c => c.meter_count).FirstOrDefault();
    ColourReading = ca.vw_ReadingsEntry.Where(s => s.ser_num == SerialNumber && s.meter_type == "Colour").Select(c => c.meter_count).FirstOrDefault();
}

Html视图:

<div id=”mono”>
  @Html.LabelFor(m => m.MonoReading)
                    @Html.TextBoxFor(m => m.MonoReading, new { @class = "form",})
                    @Html.ValidationMessageFor(m => m.MonoReading)
</div>
<div id=”colour”>
    @Html.LabelFor(m => m.ColourReading)
    @Html.TextBoxFor(m => m.ColourReading, new { @class = "form", })
    @Html.ValidationMessageFor(m => m.ColourReading)
</div>

控制器:

[HttpPost]
public ActionResult Save(M2CustomerPortal.Areas.Customer.Models.ReadingsEntry.ReadingsEntry readingForm)
{
    if (ModelState.IsValid)
    {
        var newMeterReading = new M2CPDAL.Models.CustomerPortal.CustomerReadingsEntry();

        newMeterReading.ser_num = readingForm.SerialNumber;
        **newMeterReading.MeterReading =  // Logic to go here**

        cpctx.CustomerReadingsEntries.Add(newMeterReading);
        cpctx.SaveChanges();  
    }
    return RedirectToAction("Index");
}

我要做的是,如果MonoReading有任何数据,则newMeterReading.MeterReadingColourReading的数据应显示为1。

逻辑如何在这里工作:

newMeterReading.ser_num = readingForm.SerialNumber;
**newMeterReading.MeterReading =  // Logic to go here**

正如您可以看到serialNumber的示例,它将序列号返回给数据库。

1 个答案:

答案 0 :(得分:1)

首先,我假设

var newMeterReading = new M2CPDAL.Models.CustomerPortal.CustomerReadingEntry();

应该是

var newMeterReading = new M2CPDAL.Models.CustomerPortal.ReadingEntry(readingForm.SerialNumber);

?并假设MonoReadingColourReading都可以在控制器中访问。我还假设没有数据意味着读数为0。

如果是这样,你可以这样做:

bool hasMonoReading = MonoReading.GetValueOrDefault() > 0;
bool hasColourReading = ColourReading.GetValueOrDefault() > 0;
int readingValue = 0;
if (hasColourReading)
  readingValue = 2;
else if (hasMonoReading)
  readingValue = 1;
else
  readingValue = 0;
newMeterReading.MeterReading = readingValue;

或更简洁:

bool hasMonoReading = MonoReading.GetValueOrDefault() > 0;
bool hasColourReading = ColourReading.GetValueOrDefault() > 0;
newMeterReading.MeterReading = (hasColourReading) ? 2 : (hasMonoReading) ? 1 : 0;

如果没有读数意味着读数值为空,那么你可以这样做:

newMeterReading.MeterReading = (ColourReading.HasValue) ? 2 : (MonoReading.HasValue) ? 1 : 0;