asp.net-mvc-3html-helper

How to return @Html.ActionLink


I am writing a Html Helper for my MVC 3 project.

I want to return the MvcHtmlString like "@Html.ActionLink(xxxxx)", what should I write?

Currently I have this code:

        public static MvcHtmlString SetFeaturedFor<TModel, TValue>(this HtmlHelper<TModel> htmlHelper,Expression<Func<TModel, TValue>> expression)
    {
        var isFeatured =Convert.ToBoolean(ModelMetadata.FromLambdaExpression(expression, htmlHelper.ViewData).Model.ToString());

        string result = "Html.ActionLink(Delete, DeleteComment, Admin, new { Id = @thisComment.CommentId }, null)";

        return MvcHtmlString.Create(result);
    }

It returns the whole string, but I want the rendered string. So what should I do?

Update

Looks like I can return this directly:

        public static MvcHtmlString SetFeaturedFor<TModel, TValue>(this HtmlHelper<TModel> htmlHelper,Expression<Func<TModel, TValue>> expression)
    {
        var isFeatured =Convert.ToBoolean(ModelMetadata.FromLambdaExpression(expression, htmlHelper.ViewData).Model.ToString());
        
        string indicatorText = (isFeatured) ? "Unset Featured" : "Set Featured";
        
        return htmlHelper.ActionLink(indicatorText, "SetFeaturedIncident", "Admin", null, null);
    }

Need to import System.Web.Routing namespace.


Solution

  • Remove the quotes (you want to call the function, not just store the code in a string) and the @ (that's Razor, not C# anyways). You might need to change Html to whatever you called the helper parameter in your (presumably) extension method.

    Also, Html.ActionLink already returns MvcHtmlString so you can just put it directly after return.