Loading a DIV with dynamic MvcHtmlString

735 views Asked by At

I've created a div inside a web page that needs to be filled through the jquery load function.

<div id="foo">
</div>

This is the call that should fill the div (the call is triggered by some other client side event):

$("#foo").load("/someControllerName/someActionName" + " #foo");

The someActionName method :

public MvcHtmlString someActionName()
{
    //some other irrelevant code
    MvcHtmlString returnString = new MvcHtmlString("@Html.ActionLink(" + someFileName + ", \"Download\", new { request = \"" + sameFileId + "\"})");
}

I'm having trouble at actually filling the foo div with the content of the MvcHtmlString returned by someActionName, at the point where the both someFileName and sameFileId have valid values. What am I doing wrong? Is what I'm trying to achieve even possible?

Thanks!

1

There are 1 answers

5
Faris Zacina On BEST ANSWER

If you want to run the dynamic razor expression and embed the HTML into your DIV you are doing it wrong. MvcHtmlString will just encode the expression string and return it to the client.

That action will return a Razor expression that is not comprehensible by your jQuery code. Razor is a server-side language executable by a view engine, so the only way to return a usable HTML link from your action is to execute your dynamic expression contained in the MvcHtmlString using the view engine on the server and return back a string.

One very simple way to execute your dynamic razor expression it is to use Partial Views. Your action would return just a partial view:

public PartialViewResult someActionName()
{
    var url = "/Contact";
    return PartialView("UrlView", url);
}

Your view would render your dynamic URL:

@model String
@{
    Layout = null;
}

@Html.ActionLink("Some Link", Model)

And then you can easily embed that dynamic URL into your div using $("#foo").load()

If this is too much code for you, alternatively you can try to use an open source project called RazorEngine to execute your razor statements, but i found it pretty buggy.

http://razorengine.codeplex.com/