来自try {}部分的不需要的HTML输出

时间:2014-08-25 19:56:59

标签: html asp.net exception razor

以下ASP.NET代码:

@try
    { 
      int a = 1; 
      int b = 0;
      if (a > b) 
      {
         <b>a is greater than b!</b>
      }
      a = a / b;
    }
catch
    {
      <b>there was an error</b>
    }

呈现为

 <b>a is greater than b!</b>
 <b>there was an error</b>

我想在发生异常时仅打印错误消息。请帮忙吗?

3 个答案:

答案 0 :(得分:1)

渲染的文字是正确的。首先它渲染第一行,然后你做a / b,b等于0.除以0会导致异常。

答案 1 :(得分:1)

这不是很漂亮,但它回答了问题。经过测试和运作。

    @{HtmlString  myOutput = null;
        try
        {
            int a = 1;
            int b = 0;
            if (a > b)
            {
                myOutput = new HtmlString("<b>a is greater than b!</b>"); 
            }
            a = a / b;
        }
        catch
        {
            myOutput = new HtmlString("<b>there was an error</b>");
        }
        finally
        {
            @myOutput
        }
    }

答案 2 :(得分:0)

我不是真的使用剃须刀,但这是一个猜测作为解决方案:

@try
    { 
      int a = 1; 
      int b = 0;
      if (a > b) 
      {
         a = a / b;
         <b>a is greater than b!</b>
      }
    }
catch
    {
      <b>there was an error</b>
    }

基本上,诀窍是在执行除法后输出你的消息,以便在输出发生之前发生异常。