1
votes

I have a Partial View I need loaded into a div when the page loads, does anyone know how I could do this, im pretty sure it needs to loaded via Ajax, not just as an @Html.Partial.

I have a div that I load almost all content into throughout the site, and like to be able to load just this one partial view on page load, the rest of my site uses Ajax.ActionLink to accomplish:

<div id="placeholder""></div>

It's been a really long day, I'm pretty sure I'm just braindead right now.

Your help is appreciated.

Thanks,

Mark

3

3 Answers

2
votes

You can do it as follows:

In document.ready() call your Action which will return your partial view as string and then you can replace this result using replace() in jquery:

Ajax call :

    $(document).ready(function() {
    $.ajax({
        url: "/ControllerName/ActionName",
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        success: function(data) {
            $("#placeholder").replaceWith(data);
        }
    });
});

controller:

    [HttpPost]
    public JsonResult ActionName(ModelType model)
    {
      ......
        return Json((RenderRazorViewToString("PartialViewName", model)), JsonRequestBehavior.AllowGet);
    }

    [NonAction]
    public string RenderRazorViewToString(string viewName, object model)
    {
        ViewData.Model = model;
        using (var sw = new StringWriter())
        {
            var viewResult = ViewEngines.Engines.FindPartialView(ControllerContext, viewName);
            var viewContext = new ViewContext(ControllerContext, viewResult.View, ViewData, TempData, sw);
            viewResult.View.Render(viewContext, sw);
            viewResult.ViewEngine.ReleaseView(ControllerContext, viewResult.View);
            return sw.GetStringBuilder().ToString();
        }
    }
0
votes

im pretty sure it needs to loaded via Ajax, not just as an @Html.Partial.

I'm little bit misunderstood, what difficulty in that? You just call your partial controller method through ajax and put returned data into your controller, like this:

Client:

<script src="http://code.jquery.com/jquery-1.10.2.min.js" ></script>
<script>
    $(function() {
        $.ajax({
            url: "/Home/MyPartial",
            success: function(data) {
                $("#placeholder").html(data);
            }
        });
    });
</script>

<div id="placeholder"></div>

Controller:

   public ActionResult MyPartial()
    {
        return PartialView();
    }

MyPartial.cshtml:

<div>my partial</div>
-2
votes

If you are using jQuery you could do something like this:

$('#foo').load('path/to/your/partial/file');