开发者

Add HTML content to a view Dynamically in MVC (without AJAX)

开发者 https://www.devze.com 2023-03-19 13:40 出处:网络
I have many static HTML files (Lets say 1.html to 100.html). Is there any way that I can create a link like Files/get/1 (where \"Files\" is the controller and \"get\" is the action). Read the file bas

I have many static HTML files (Lets say 1.html to 100.html). Is there any way that I can create a link like Files/get/1 (where "Files" is the controller and "get" is the action). Read the file based on the passed id and put the file's content inside my site layout and send it to user.

In this way the format of those Html file will be preserved, and I wouldn't need to create a View for each file.

I am new to MVC and will appreciate any suggestion/hint. Le开发者_如何学Pythont me know if the question is not clear.

Thanks for the help in advance. Reza,

Edit: Added what I ended up doing.

Answer: So I used what Darin said below, combined it with a little bit of jQuery and got exactly what I needed. Which was loading static HTML files inside my layout. Here is the sample of what I did:

First I created two methods in my Controller:

    public ActionResult GetHelp(String id)
    {
        var folder = Server.MapPath(Config.get().Help_Folder);
        var file = Path.Combine(folder, id + ".html");
        if (!System.IO.File.Exists(file))
        {
            return HttpNotFound();
        }
        return Content(System.IO.File.ReadAllText(file), "text/html");

    }


    public ActionResult GetHelper(String id)
    {

        ViewBag.helpPath = id; 
        return View();

    }

Then I created a view called GetHelper, which uses my layout, and added the below code to it:

<script type="text/javascript">

$(function () {
    var path = "@ViewBag.helpPath"
    path = "@Url.Content("~/Helps/GetHelp/")" + path;
    $('#help-content').load(path);

});
</script>

<div id="help-content">

</div>

And it works perfectly. The only downside is for each page we get two server requests :(


Something among the lines:

public class FileController : Controller
{
    public ActionResult Index(string id)
    {
        var folder = Server.MapPath("~/SomePathForTheFiles");
        var file = Path.Combine(folder, id + ".html");
        if (!System.IO.File.Exists(file))
        {
            return HttpNotFound();
        }
        return Content(System.IO.File.ReadAllText(file), "text/html");
    }
}

and if you wanted the user do download those files:

return File(file, "text/html", Path.GetFileName(file));

and because those are static files you could cache them by decorating your controller action with the [OutputCache] attribute:

[OutputCache(Location = OutputCacheLocation.Downstream, Duration = 10000, VaryByParam = "id")]
public ActionResult Index(string id)
0

精彩评论

暂无评论...
验证码 换一张
取 消