gsiradze
gsiradze

Reputation: 4733

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?

Upvotes: 0

Views: 123

Answers (4)

Dallas
Dallas

Reputation: 504

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); 
}

Upvotes: 0

Chirag Arvadia
Chirag Arvadia

Reputation: 1200

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

Upvotes: 2

Chatra
Chatra

Reputation: 3139

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

Upvotes: 0

Emil Lundin
Emil Lundin

Reputation: 597

Assuming the return type is ActionResult

return Content("Percentage must be 100");

Upvotes: 0

Related Questions