简体   繁体   中英

How to override @url.content in MVC?

I have an MVC application. After I finished the web site I need to change @url.content behavior.

So I need to override @url.content in all of my website application. How can I do it?

<script src="@Url.Content("~/Scripts/jquery-1.7.1.js")"></script>
<script src="@Url.Content("~/Scripts/ui/jquery.ui.core.js")"></script>
<script src="@Url.Content("~/Scripts/ui/jquery.ui.widget.js")"></script>
<script src="@Url.Content("~/Scripts/ui/jquery.ui.tabs.js")"></script>
<script src="@Url.Content("~/Scripts/ui/jquery.ui.accordion.js")"></script>
<script src="@Url.Content("~/Scripts/jquery.nivo.slider.js")"></script>
<script src="@Url.Content("~/Scripts/jwplayer.js")"></script>

I think your best bet here would be just to create another UrlHelper Extension Method.

public static class MyExtensions
{
    public static string ContentExt(this UrlHelper urlHelper, string Content)
    {
        // your logic
    }
}

MHF,

As mentioned in my comments above, i 'feel' you should create a bespoke html.image() helper, rather than try to override the url.content() helper, given that your problem is related to images, and not url.content() per se. here's how i'd approach this:

public static partial class HtmlHelperExtensions
{
    public static MvcHtmlString Image(this HtmlHelper helper,
                                string url,
                                object htmlAttributes)
    {
        return Image(helper, url, null, htmlAttributes);
    }
    public static MvcHtmlString Image(this HtmlHelper helper,
                                    string url,
                                    string altText,
                                    object htmlAttributes)
    {
        TagBuilder builder = new TagBuilder("image");

        var path = url.Split('?');
        string pathExtra = "";

        // NB - you'd make your test for the existence of the image here
        // and create it if it didn't exist, then return the path to 
        // the newly created image - for better or for worse!! :)

        if (path.Length > 1)
        {
            pathExtra = "?" + path[1];
        }
        builder.Attributes.Add("src", VirtualPathUtility.ToAbsolute(path[0]) + pathExtra);
        builder.Attributes.Add("alt", altText);
        builder.MergeAttributes(new RouteValueDictionary(htmlAttributes));
        return MvcHtmlString.Create(builder.ToString(TagRenderMode.SelfClosing));
    }
}   

useage:

@Html.Image("~/content/images/ajax-error.gif", new{@class="error_new"})

Now, the above is purely a 'lift' from an old mvc project, with a comment added to give a hint as to what you might do. I haven't tested this in any way, so caveat emptor :)

good luck

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM