0

Trying to use a html helper I found here on the first answer:

enter link description here

Heres the controller part:

 public static class HtmlHelpers
{
    public static MvcHtmlString DisplayWithBreaksFor<TModel, TValue>(this HtmlHelper<TModel> html, Expression<Func<TModel, TValue>> expression)
    {
        var metadata = ModelMetadata.FromLambdaExpression(expression, html.ViewData);
        var model = html.Encode(metadata.Model).Replace("\r\n", "<br />\r\n");

        if (String.IsNullOrEmpty(model))
            return MvcHtmlString.Empty;

        return MvcHtmlString.Create(model);
    }
}

and in the view I use:

@using HtmlHelpers

and

@Html.DisplayWithBreaksFor(m => m.MultiLineField)

But I am getting an error on both

For the first:

"The type or namespace name 'HtmlHelpers' could not be found (are you missing a using directive or an assembly reference?)"

For the second:

"'System.Web.Mvc.HtmlHelper>' does not contain a definition for 'DisplayWithBreaksFor' and no extension method 'DisplayWithBreaksFor' accepting a first argument of type"

"'System.Web.Mvc.HtmlHelper>' could be found (are you missing a using directive or an assembly reference?)"

2
  • HtmlHelpers is a class name, @using expects a namespace. Also, that name clashes with one from the framework. Commented Jan 23, 2019 at 9:33
  • Have you used the full path here @using HtmlHelpers or just this? Commented Jan 23, 2019 at 10:01

2 Answers 2

1

You added the wrong namespace. I think you should not put the method in the controller. Just create a new class. So you can reuse code better. Here is a sample. You can refer. Hope to help, my friend :))

1) I created a new class that have namespace is MvcExam.UtilitiesClass

namespace MvcExam.UtilitiesClass
{
    public static class HtmlHelpers
    {
        public static MvcHtmlString DisplayWithBreaksFor<TModel, TValue>(this HtmlHelper<TModel> html, Expression<Func<TModel, TValue>> expression)
        {
            var metadata = ModelMetadata.FromLambdaExpression(expression, html.ViewData);
            var model = html.Encode(metadata.Model).Replace("\r\n", "<br />\r\n");

            if (String.IsNullOrEmpty(model))
                return MvcHtmlString.Empty;

            return MvcHtmlString.Create(model);
        }
    }
}

2) In a View

@using MvcExam.UtilitiesClass

@Html.DisplayWithBreaksFor(m => m.Name)
Sign up to request clarification or add additional context in comments.

1 Comment

@Conor8630: Well played, my friend :))
0

You have to use the full namespace:

@using YourProjectName.YourAssemblyName.FolderNameWhereYourClassLives;

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.