简体   繁体   English

如何使用MVC 3(Razor)向图像添加动态源

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

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. 我是Mvc的新手,我的图像可能有正确或错误的图像,具体取决于用户给出的答案。

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. 这完美地运作但我认为必须有一个更清洁/更好的方法来做这样的事情。

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)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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