Welcome...



...All those moments will be lost in time, like tears in rain....

- soliloquy from Blade Runner


Bits and bytes do get lost, awash in the rain of data flow that is Internet. They slip away from us, never to found again... some of them will be captured here, many more will not... like tears in rain...



Tuesday, October 8, 2013

MVC - How to get ModelState collection in the View

ValidationSummary is nice way of displaying errors on the Model.
Sometimes it's useful to query ModelState collection itself, to see it's content.
This code will display all errors that are in collection.
Note: This is for Errors only, Exceptions are in different collection - item.Value.Exceptions...

<table>
  <tr><td>Model State</td></tr>
    @foreach (var item in ViewContext.ViewData.ModelState)
    {
        if (item.Value.Errors.Any())
        {
            <tr>
                <td><b>@item.Key</b></td>
                <td>@((item.Value == null || item.Value.Value == null) ? "<null>" : item.Value.Value.RawValue)</td>
                <td>In</td>
                <td>Error: @(string.Join("; ", item.Value.Errors.Select(x => x.ErrorMessage)))</td>
            </tr>
        }
    }
</table> 
 

No comments:

Post a Comment