Reputation: 3156
I am passing my model errors via the ViewBag
. In my controller I am passing a List<string>
that does contain values (_modelErrors
) to the ViewBag
and then I am trying to display this in my view. When I debug in the view, my ViewBag
does contain a _modelErrors
dictionary with values, but my errors are not being rendered.
From my controller:
ViewBag._modelErrors = _modelErrors;
In my view I have tried all of these methods and yet no markup is rendered.
@try
{
foreach (string er in ViewBag._modelErrors)
{
Response.Write(er.ToString());
@Html.DisplayText(er)
@Html.DisplayText(er.ToString())
@er.GetType()
@er.ToString();
er.ToString();
}
}
catch(Exception e){}
Upvotes: 1
Views: 789
Reputation: 6948
That's a dirty code, dude! Take a look at @Html.ValidationSummary
and @Html.ValidationMessageFor
Well, some codes here to clarify stuff:
[HttpPost]
public ActionResult MyAction(ModelClass inputModel)
{
if (ModelState.IsValid)
{
//for example we're trying to save our data to db
var result = _myRepository.saveStuff(inputModel);
if (result)
return RedirectToAction("someAction");
ModelState.AddModelError(string.Empty, "An error occured, check input data");
}
return View(inputModel);
}
Also you can specify key (which is your model field name) instead of string.Empty -> so you'l see error message under specified field (as default), but basically what people do is exluding property errors from validation summary (@Html.ValidationSummary(true)
) - so you get just general errors in that field. Hope it'l help
Upvotes: 3
Reputation: 5895
Use this:
(string er in (List<string>)(ViewBag._modelErrors))
But was said this is bad practice. Also catching exceptions this way is so wrong...
Upvotes: 1