Reputation: 345
Trying to use a html helper I found here on the first answer:
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?)"
Upvotes: 0
Views: 387
Reputation: 2245
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)
Upvotes: 1
Reputation: 552
You have to use the full namespace:
@using YourProjectName.YourAssemblyName.FolderNameWhereYourClassLives;
Upvotes: 0