2

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:

@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.

1 Answer 1

9

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)
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.