2015-03-31 26 views
0

我收到List<int> percentage作爲參數POST控制器如果變量不是我所期望的,則顯示錯誤消息

我這樣做:

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

現在我想,與其返回查看();它顯示錯誤消息,百分比必須是100。我怎樣才能做到這一點?

回答

2

在viewbag

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

把這個代碼中要顯示的消息

+0

請標明的答案,如果它的正確接受 – 2015-03-31 13:03:28

0

假設返回類型的ActionResult

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

在ViewBag,ViewData的或模型將消息和與jQuery diplay它。 像這樣

ViewBag.Error = "percentage must be 100"; 

JavaScript的觀點

var ErrorMessage = @ViewBag.Error; 

jQuery的

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