【问题标题】:Display error message if variable isn't what i expect如果变量不是我所期望的,则显示错误消息
【发布时间】:2015-03-31 12:47:56
【问题描述】:

我在 POST 控制器中收到 List<int> percentage 作为参数。

我正在这样做:

var prc = 0;
var prcCount = 0;
foreach (var pr in percentage)
{
    prc += pr;
    prcCount++;
}
if (prc != 100)
    return View();

现在我希望它代替 return View(); 它显示 percentage must be 100 的错误消息。我该怎么做?

【问题讨论】:

    标签: c# asp.net-mvc error-handling data-annotations


    【解决方案1】:

    在视图包中添加消息

    if (prc != 100)
        {
          ViewBag.PercentageMessage = "your error message."
          return View();
        }
    

    并在视图中检查 ViewBag.PercentageMes​​sage 是否不为空且为空,然后在标签中显示消息。

    if (ViewBag.PercentageMessage != null)
    {
        string message = Convert.ToString(ViewBag.PercentageMessage);
        if(message != "")
        {
          <label>@message</label>
        }
    }
    

    将此代码放在您要显示消息的位置

    【讨论】:

      【解决方案2】:

      假设返回类型为 ActionResult

      return Content("Percentage must be 100");
      

      【讨论】:

        【解决方案3】:
         string Percentage = "Percentage must be 100";
         if (prc != 100)
           return Json(Percentage);
        

        【讨论】:

          【解决方案4】:

          将消息放入 ViewBag、ViewData 或模型中,并用 jquery 显示。 像这样的

          ViewBag.Error = "percentage must be 100";
          

          javascript 视图

          var ErrorMessage = @ViewBag.Error;
          

          jquery

          if (ErrorMessage.length>0) {   
                 $("#divError").show().html(ErrorMessage); 
          }
          

          【讨论】:

            猜你喜欢
            • 2016-07-08
            • 2019-02-17
            • 2012-12-31
            • 1970-01-01
            • 1970-01-01
            • 2013-04-21
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            相关资源
            最近更新 更多