Blog posts about mvc

  • Show text line breaks in ASP.NET MVC Razor view

    December 10, 2014 | Tags: CSS, ASP.NET, MVC, Snippet

    If you have a string with line breaks and want to show that text with the line-breaks intact in your Razor-based view, you can do this without replacing all \r\n with <br/>-tags. Instead present the text in an element that has the style property white-space set to pre-line. You should really add a class like:

    <style>
    .line-breaks { white-space:pre-line; }
    </style>

    <span class="line-breaks">@Model.MyText</span>

  • HttpContext.Current not working in ASP.NET MVC

    December 09, 2014 | Tags: Troubleshooting, ASP.NET, MVC, C#

    This is most likely because it's no resolving to the correct class. Instead of using System.Web.HttpContext it tries to resolve towards System.Web.Mvc.Controller.HttpContext. The way to fix this is to prefix HttpContext.Current with System.Web so that your usage looks like: System.Web.HttpContext.Current


  • Get all model validation errors in ASP.NET MVC

    December 08, 2014 | Tags: C#, ASP.NET, MVC, Snippet, Validation

    In ASP.NET MVC you can get a list of all validation errors for your model from the ModelState:

      if (!ModelState.IsValid) {
        var modelErrors = new List<string>();
        foreach (var modelState in ModelState.Values) {
          foreach (var modelError in modelState.Errors) {
            modelErrors.Add(modelError.ErrorMessage);
          }
        }
        // do something with the error list :)
      }