Reputation: 1370
I want to display error messages in my view. What is the best way to do this?
What replaces the "???" in my code below? I don't want to simply use Html.ValdiationSummary because right now I'm thinking I need to process the list myself and place certain error messages in different places. For example, the code below would actually need to be expanded to put some of the error messages in a floating div, while others may be displayed at the top of the page.
Is there a better way to do this altogether? e.g. Should I be using an entirely different approach to passing error messages from my controller to the view?
My Controller:
public ActionResult ForgotUsername(ForgotUsernameModel model)
{
...
if (!Users.CheckUsername(model.UserName)) {
ModelState.AddModelError("", "That username does not exist.");
}
....
return View(model);
}
My View:
....
<%
if (???) {
foreach (KeyValuePair<string, ModelState> item in ViewData.ModelState) {
if (item.Value != null && item.Value.Errors != null && item.Value.Errors.Count > 0) {
foreach (ModelError e in item.Value.Errors) {
Response.Write(String.Format("<div>{0}</div>", e.ErrorMessage));
}
}
}
}
%>
Upvotes: 0
Views: 3031
Reputation: 1039508
<% if (!ViewData.ModelState.IsValid) { %>
<%= Html.ValidationSummary(true) %>
<% } %>
or simply:
<%= Html.ValidationSummary(true) %>
Upvotes: 3