HiveBrain v1.2.0
Get Started
← Back to all entries
debugcsharpMinor

Replacing div if there is any validation error connected with the div value

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
errorthewithanydivvalidationvaluereplacingconnectedthere

Problem

I have an input group:


    
        @Html.DisplayNameFor(m => m.StorageId)
    
    @if(ViewData.ModelState["StorageError"] !=null && ViewData.ModelState["StorageError"].Errors.Count>0)
    {
        
            @Html.DropDownList("storageId", null, new { @class = "form-control",@style="border-color:red" })
        
    }
    else
    {
        
            @Html.DropDownList("storageId", null, new { @class = "form-control" })
        
    }


As you can see, if there are no errors, the site should render div without a red border and tooltip.

Do you think it's efficient and good-looking enough to leave it as it is, or does it need to be rewritten?

Solution

Basically, 95% of your code is the same between the two sections, so I'd prefer to use just a single instance with a bool on the page.

@{ 
    var error = ViewModel.ModelState["StorateError"];
    var hasErrors = error != null && error.Errors.Any();
}

        @Html.DropDownList("storageId", null, new { @class="form-control",
            @style=" @( hasErrors ? "border-color:red", string.Empty ) })


You should also get into the habit of using .Any() instead of Count() > 0 as Any will stop iterating after it finds the first item that matches the filtering (usually not a big deal, but the collection could get rather large, and it's a minor change to coding that could give big performance enhancements).

The only other thing I might recommend would be to have a CSS class for border-color:red instead of inline styling.

Code Snippets

@{ 
    var error = ViewModel.ModelState["StorateError"];
    var hasErrors = error != null && error.Errors.Any();
}

<div class="a" title="@( hasErrors ? error.Errors[0].ErrorMessage : string.Empty" )
    data-toggle="tooltip" data-placement="left" id="storage">
        @Html.DropDownList("storageId", null, new { @class="form-control",
            @style=" @( hasErrors ? "border-color:red", string.Empty ) })
</div>

Context

StackExchange Code Review Q#58257, answer score: 4

Revisions (0)

No revisions yet.