2

Is there a way to return HtmlHelper object from controller to view?

In code:

Controller:

public ActionResult SomeFunc(int id)
    {
        if (condition)
            return Content();//here i would like to send Html.ActionLink("Text", "Action")
        else
            return Content();
    }

The link will get handle in javascript:

        $.get("", { id: $("#id").val() }).
    done(function (data) {
        if (data != 0) {
            $("#someDOMID").val(data);
        }
    });
3
  • the most easier it's creating a partial view and consume from client side via Ajax, but I think it is possible to use helper in action method and return html from there. Commented Nov 2, 2017 at 14:10
  • there is need for server logic to deside which link to generate Commented Nov 2, 2017 at 14:12
  • partial view can have this code embedded, or put it in controller and pass ViewBag or model Commented Nov 2, 2017 at 14:13

2 Answers 2

2

If you want the content to contain a raw html string then you can create a function to render a partial to a string serverside and return that.

You could then take it another step and create a generic ActionLinkPartial that contained one embedded @Html.ActionLink and accepted a model that had your action link configuration settings.

Something like...

   protected string RenderPartialViewToString(string viewName, object model)
    {
        if (string.IsNullOrEmpty(viewName))
            viewName = ControllerContext.RouteData.GetRequiredString("action");

        ViewData.Model = model;

        using (StringWriter sw = new StringWriter())
        {
            ViewEngineResult viewResult = ViewEngines.Engines.FindPartialView(ControllerContext, viewName);
            ViewContext viewContext = new ViewContext(ControllerContext, viewResult.View, ViewData, TempData, sw);
            viewResult.View.Render(viewContext, sw);

            return sw.GetStringBuilder().ToString();
        }
    }

And use a model like...

public class ActionLinkModel
{
   public string Text{get;set}
   public string Action{get;set;}
}

Invoke it like...

var html = this.RenderPartialViewToString("Partials/Html/ActionLinkPartial", model);
Sign up to request clarification or add additional context in comments.

Comments

1

If you only need to send a link as mentioned in your question then try this:

public ActionResult GetLink()
{
    string url = Url.Action("Index", "Home", new { id = 1 });
    return Content(url);
}

Otherwise, it's better to use the Partial View approach.

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.