简体   繁体   中英

Display error message if variable isn't what i expect

I'm receiving List<int> percentage as parameter in POST controller .

I'm doing that:

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

Now I want that instead of return View(); it display error message that percentage must be 100 . How can I do that?

add message in viewbag

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

and in view check if ViewBag.PercentageMessage is not null and empty then display message in label.

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

put this code where you want to display message

假设返回类型为ActionResult

return Content("Percentage must be 100");
 string Percentage = "Percentage must be 100";
 if (prc != 100)
   return Json(Percentage);

Put message in ViewBag, ViewData or model and diplay it with jquery. Something like this

ViewBag.Error = "percentage must be 100";

javascript view

var ErrorMessage = @ViewBag.Error;

jquery

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM