Reputation: 966
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);
}
});
Upvotes: 2
Views: 271
Reputation: 6683
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.
Upvotes: 1
Reputation: 15155
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);
Upvotes: 2