将ModelError发送到View

时间:2017-06-25 12:18:34

标签: c# asp.net-mvc

我有<div class="row"> <div id="header" class="col-12"> <h1>Hey</h1> </div> </div> <div class="row"> <div id="menu" class="col-3"> <ul> <li>MENÚ 1</li> <li>MENÚ 2</li> <li>MENÚ 3</li> </ul> </div> <div id="content" class="col-6"> <h2>Sup?</h2> <p> Content goes here </p> </div> <div id="sidebar" class="col-3"> <p>This is a sidebar!</p> </div> </div>查看。我在控制器中有一个方法,可以返回ModelError:

Index.cshtml

问题是,当页面重新加载时,[HttpPost] public ActionResult Create(string folderName) { try { //some stuff } catch //if folder with same name already exist { ModelState.AddModelError("", "Forlder with name " + folderName + "already exist"); return Redirect(HttpContext.Request.UrlReferrer.AbsoluteUri); } return Redirect(HttpContext.Request.UrlReferrer.AbsoluteUri); }

中没有任何内容
@Html.ValidationSummary()

1 个答案:

答案 0 :(得分:0)

在您的情况下,ModelState不起作用。
您可以使用TempData ModelState.AddModelError()使用TempData["YourKey"].Add(Forlder with name " + folderName + "already exist") 然后在_Layout.cshtml中使用:

@{ string notification = (string)TempData["YourKey"];}
if(!string.IsNullOrEmpty(notification ){
     @notification 
}