0

当用户输入正确时,我正在尝试进行验证,我使用带有黑色文本的标签来显示。相反,当用户输入不正确时,我在 ASP.NET 中将错误消息显示在另一个带有红色文本的标签中。这是一个 3 层程序。这是我的表示层中的代码:

    protected void btn_submit_Click(object sender, EventArgs e)
{
    ToolsBLL calcBMI = new ToolsBLL();
    lbl_result.Text = "";
    lbl_invalid.Text = "";
    if (calcBMI.Valid == true)
    { 
        lbl_result.Text = calcBMI.calcBMI(tb_height.Text, tb_weight.Text);
    }
    else if (calcBMI.Valid == false)
    {
        lbl_invalid.Text = calcBMI.calcBMI(tb_height.Text, tb_weight.Text);
    }

}

它会调用BusinessLogicLayer中名为Valid的getter和setter来检查输入是否有效。这是我的 BusinessLogicLayer 中的代码:

    public static Boolean valid;
    public Boolean Valid
    {
        get { return valid; }
        set { valid = value; }
    }

    public string calcBMI(string sheight, string sweight)
    {
        decimal height = 0;
        decimal weight = 0;
        string bmiResultDesc = "";
        decimal bmi = 0;
        ToolsBLL.valid = true;

        if (sheight == "" && sweight == "")
        {
            ToolsBLL.valid = false;
            bmiResultDesc = "Height/Weight cannot be blank.";  
        }
        else
        {
            try
            {
                height = decimal.Parse(sheight);
                weight = decimal.Parse(sweight);
            }
            catch
            {
                ToolsBLL.valid = false;
                bmiResultDesc = "Height/Weight must be in numeric.";
            }
        }

        if (bmiResultDesc == "")
        {
            if (height <= 0)
            {
                ToolsBLL.valid = false;
                bmiResultDesc = "Invalid height";
            }
            else if (weight <= 0)
            {
                ToolsBLL.valid = false;
                bmiResultDesc = "Invalid weight";
            }
            else
            {
                BMICalculator.BMICalculator bmiCalc = new BMICalculator.BMICalculator();
                bmi = bmiCalc.computeBMI(height, weight);
                if (bmi <= 0)
                {
                    ToolsBLL.valid = false;
                    bmiResultDesc = "Error in consuming web services.";                   
                }
                else
                {
                    ToolsBLL.valid = true;
                    bmiResultDesc = "Your BMI is " + bmi.ToString();  
                }
            }

        }
        return bmiResultDesc;
    }

我使用 getter 和 setter 来设置布尔值。我不确定我是否以正确的方式做事,因为我的 BMICalculator 表现得很奇怪。例如,当我输入正确的输入时,有时显示为黑色,有时显示为红色。我不知道为什么会这样。

提前致谢。

4

2 回答 2

0
if (calcBMI.Valid == true)
{ 
    lbl_result.Text = calcBMI.calcBMI(tb_height.Text, tb_weight.Text);
    lbl_result.ForeColor = Color.Black;

}
else if (calcBMI.Valid == false)
{

    lbl_result.Text = "Your input is invalid";
    lbl_result.ForeColor = Color.Red;
}
于 2013-11-11T08:42:45.293 回答
0

如果您想获得有关某事有效性的最新信息,您应该在需要时检查有效性,而不是阅读一些过去告诉您有关有效性的属性。因此,只需在执行计算之前添加方法 Validate 并在其中检查验证。使用验证属性来检查身高和体重是否为数字是个好主意。

于 2013-11-11T08:47:48.817 回答