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)
精彩评论