2

I've got the following snippet of Razor code, that exists in probably 15 different pages, that I'd like to reuse, if possible:

    <div class="col-xs-12">
        @if (@Model.Rating == 0)
        {
            <img src="/Images/Rating/NoRating.jpg" alt="" width="125">
        }
        else if (@Model.Rating == 1)
        {
            <img src="/Images/Rating/One.jpg" alt="" width="125">
        }
        else if (@Model.Rating == 2)
        {
            <img src="/Images/Rating/Two.jpg" alt="" width="125">
        }
        else if (@Model.Rating == 3)
        {
            <img src="/Images/Rating/Three.jpg" alt="" width="125">
        }
        else if (@Model.Rating == 4)
        {
            <img src="/Images/Rating/Four.jpg" alt="" width="125">
        }
        else if (@Model.Rating == 5)
        {
            <img src="/Images/Rating/Five.jpg" alt="" width="125">
        }
    </div>

What I would love to be able to do is to call a method and have the method return this code where I have it in my Razor .cshtml file. The method would also have to accept a parameter. In this case, the parameter would be a rating value of between 0 and 5. I would then replace all occurrences of @Model.Rating with the parameter value. Is it possible to do this? I'd rather not have to resort to a partial view if possible.

3 Answers 3

3

What I would love to be able to do is to call a method and have the method return this code where I have it in my Razor .cshtml file. The method would also have to accept a parameter. In this case, the parameter would be a rating value of between 0 and 5. I would then replace all occurrences of @Model.Rating with the parameter value. Is it possible to do this?

Solution 1:

You can create an extension method of HtmlHelper class like this :

public static class RatingExtensions
{
    public static MvcHtmlString Rating(this HtmlHelper helper, short rating)
    {
        var imageSrc = "/Images/Rating/";
        switch (rating)
        {
            case 0:
                imageSrc += "NoRating.jpg";
                break;

            case 1:
                imageSrc += "One.jpg";
                break;


            // And so on....

            default:
                throw new IndexOutOfRangeException(string.Format("The following rating: {0} is not expected.",
                    rating));
        }

        return new MvcHtmlString(String.Format("<img src='{0}' alt='' width='125' />", imageSrc));
    }
}

In your view after importing the namespace of your extension method into the view, you call your extension method by writing this line:

@Html.Rating(Model.Rating)

Solution 2:

Just create a partial view and put it into the Shared sub-folder of your Views folder. Lets name it _Ratring.cshtml. The content of this file muste be the following (Notice @model directive which is in short type):

@model short
@{
    var imageSrc = "/Images/Rating/";
    switch (Model)
    {
        case 0:
            imageSrc += "NoRating.jpg";
            break;

        case 1:
            imageSrc += "One.jpg";
            break;

        // And so on....

        default:
            throw new IndexOutOfRangeException(string.Format("The following rating: {0} is not expected.",
                Model));
    }
}

<div class="col-xs-12">
    <img src="@imageSrc" alt="" width="125">
</div>

You use this solution in your view by call Html.RenderPartial method liek this :

@{
    Html.RenderPartial("_Rating", Model.Rating);
}

Solution 1 is better because you can move the extension method in its own assembly project and use it accross multiple projects.

3
  • 1
    Very nice. Answers like this is what makes SO great. Nov 21, 2015 at 19:47
  • You're welcome :) If it satisfy your question, accept it as an answer to your question, please ;-) Nov 21, 2015 at 19:57
  • My SO reputation score should assure you I don't forget to accept answers that satisfy the question :). I just want to implement it first to make sure it works. Might be a day or two. Nov 21, 2015 at 20:00
1

Option 1

You may create a custom Html helper method. I would prefer to rename the image name from One.jpg to 1.jpg so that you do not need to write much code from the number passed into the string representation of that. You can simply relate your Model.Rating value to the image name as they directly match.

But if you still want to keep the image names as the string way, You may need to write a switch statement inside your method to convert the integer value to the string value (1 to One, 2 to Two etc..). The problem with this approach is, If you ever add a new rating like 12 or 13, you need to go to this file and update your switch statements again ! So i prefer the first approach of renaming the image names to match with the numeric representation of Model.Rating value

public static class MyCustomImageExtensions
{
    public static MvcHtmlString RatingImage(this HtmlHelper helper, int imageId,
                                                                      string alt,int width)
    {
        var path = "Images/Rating/NoRating.jpg";
        if (imageId > 0)
        {
            path = string.Format("Images/Rating/{0}.jpg", imageId);
        }
        return new MvcHtmlString(string.Format("<img src='{0}' alt='{1}' width='{2}'>"
                                                                  , path, alt, width));

    }
}

You may call it in your razor view like

@Html.RatingImage(Model.Rating,"alt test",250)

You may add the Alternate text property and width to your model so that you do not need to hard code it in your main view.

Option 2

Since you are not doing much logic inside the helper method, you may simply use partial view where you will have the markup you want to use and pass the model properties to that.

1
  • I always recommend people should use the TagBuilder to create html elements, less error prone. Nov 21, 2015 at 20:19
-1

I would change a lot, but it's really worth it. Create your own ModelMetadataProvider.

public class MyModelMetaDataProvider : DataAnnotationsModelMetadataProvider
{
    public override ModelMetadata GetMetadataForProperty(Func<object> modelAccessor, Type containerType, string propertyName)
    {
        var result = base.GetMetadataForProperty(modelAccessor, containerType, propertyName);

        if (string.IsNullOrEmpty(result.TemplateHint)
            && typeof(Enum).IsAssignableFrom(result.ModelType))
        {
            result.TemplateHint = result.ModelType.ToString();
        }

        return result;
    }
}

Register it in the global.asax

ModelMetadataProviders.Current = new MyModelMetaDataProvider();

Create an Enum:

public enum StarRating
{
    NoRating = 0,
    One = 1,
    Two = 2,
    Three = 3,
    Four = 4,
    Five = 5
}

Update your model

public class SomeMethodViewModel
{
  public StarRating Rating { get; set; }
}

Create a Display template

/Views/Shared/DisplayTemplates/StarRating.cshtml

@model StarRating

<img src="/Images/Rating/@(Model.ToString()).jpg" alt="" width="125">

In your view:

@Html.DisplayFor(m => m.Rating)

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.