Asp.net core setting background in <form>

Issue

Hey guys we’re learning with a friend how to code and we’ve just moved into front-end from back-end stuff. At the very beginning we faced a problem we can’t solve. We want to have a image in background of this form:

<form asp-controller="Notes" asp-action="Index" method="get">
        <p1>
            Hashtag: @Html.DropDownList("noteHashtag", "All")
            Name: <input type="text" name="SearchString">
            <input type="submit" value="Filter" />
        </p1>
    </form>

we tried doing stuff like adding to p1 or form this:

style="background-image:url(//images///images/SearchBg.jpg)"

but its not working. We’re learning in ASP.NET core 1.0.0.
Thanks for replies

Solution

This is likely because you are targeting your image via a relative URL, which is going to be made relative to the View that it appears in.

This would generally be resolved by using the Url.Content() helper method to avoid any relative pathing issues by using an absolute path instead :

<form ... style="background: url('@Url.Content("~/images/images/SearchBg.jpg")');">
   <!-- Your content here -->
</form>

Alternative: Consider Using CSS Styles

You can resolve your relative pathing issues in this case by not referencing your images relative to the Views they are defined in but instead referencing them within your CSS file.

Consider creating a style in your CSS file that resembles the following :

.search-background {
    /* Ensure that the relative URL used is from your CSS file to the target image! */
    background: url('/images/searchBg.jpeg');
}

As long as your URL is correct there, then you should have no problem simply adding a class attribute onto your form to resolve the image properly and apply the background :

<form ... class='search-background'>
    <!-- Your content here -->
</form> 

Answered By – Rion Williams

Answer Checked By – Robin (AngularFixing Admin)

Leave a Reply

Your email address will not be published.