开发者

How to add a dynamic source to an image using MVC 3 (Razor)

开发者 https://www.devze.com 2023-04-02 05:15 出处:网络
I\'m new to Mvc and I\'m having an image that can have a correct or wrong image depending on the answer the user gives.

I'm new to Mvc and I'm having an image that can have a correct or wrong image depending on the answer the user gives.

This is my current code:

开发者_Python百科
@if (Model.IsCorrect) 
    {
        <img src="@Url.Content(@"~/Content/images/Default_Correct.png")" alt="correct" />
    }
    else
    {
        <img src="@Url.Content(@"~/Content/images/Default_Wrong.png")" alt="wrong" /> 
    }

This works perfectly but I think there must be a much cleaner/better way to do something like this.


If you are like me and hate polluting your views with spaghetti code you could write a custom helper:

public static class ImageExtensions
{
    public static IHtmlString MyImage(this HtmlHelper htmlHelper, bool isCorrect)
    {
        var urlHelper = new UrlHelper(htmlHelper.ViewContext.RequestContext);
        var img = new TagBuilder("img");
        if (isCorrect)
        {
            img.Attributes["alt"] = "correct";
            img.Attributes["src"] = urlHelper.Content("~/Content/images/Default_Correct.png");
        }
        else
        {
            img.Attributes["alt"] = "wrong";
            img.Attributes["src"] = urlHelper.Content("~/Content/images/Default_Wrong.png");
        }
        return MvcHtmlString.Create(img.ToString(TagRenderMode.SelfClosing));
    }
}

and in your view simply:

@Html.MyImage(Model.IsCorrect)
0

精彩评论

暂无评论...
验证码 换一张
取 消