Amit
Amit

Reputation: 319

Render partial view without creating an ActionResult

This is my controller

public class HomeController : Controller
    {
        public ActionResult Index()
        {
            return View();
        }

        public ActionResult ShowPartial()
        {
            return PartialView("_View1");
        }
    }

This is my Index View

<script type="text/javascript">
    function myFunction() {
        $("#div1").load('@Url.Action("ShowPartial", "Home")');
    }
</script>
<div id="div1">
</div>
@section footerButton {
    <input type="button" id="button1" value="button" onclick="myFunction()" />
}

This is my layout page

<body>
    <div style="height: 10%; background-color: whitesmoke; text-align: center">
        Header
    </div>
    <div style="height: 80%; background-color: white; text-align: center">
        @RenderBody()
    </div>
    <div style="height: 10%; background-color: whitesmoke; text-align: center">
        @RenderSection("footerButton", false)
    </div>
</body>

I have created a partial view page where I have written a word "Hello". I done rendering the partial view on button click. I have used an actionResult named ShowPartial as you can see it above. Now my problem is that i want the same output without creating an Actionresult. Please help.

Upvotes: 0

Views: 4482

Answers (3)

uhum
uhum

Reputation: 176

You can try this:

 @{ Html.RenderPartial("_PartialViewName"); }

You can use a model in your view as well and pass it directly from the view that is calling the partial one.

Upvotes: 1

vtforester
vtforester

Reputation: 683

If you return a String instead of an ActionResult you could use the following to generate the string. You can, optionally, put this method on a base controller so that you maximize re-use.

public string RenderPartialViewToString(string viewName, object model)
{
    this.ViewData.Model = model;
    try
    {
        using (StringWriter sw = new StringWriter())
        {
            ViewEngineResult viewResult = ViewEngines.Engines.FindPartialView(this.ControllerContext, viewName);
            ViewContext viewContext = new ViewContext(this.ControllerContext, viewResult.View, this.ViewData, this.TempData, sw);
            viewResult.View.Render(viewContext, sw);

            return sw.GetStringBuilder().ToString();
        }
    }
    catch (System.Exception ex)
    {
        return ex.ToString();
    }
}

and, then you call it from your method as such:

public String ShowPartial()
{
    return RenderPartialViewToString("_View1", null);
}

Upvotes: 1

Eray Aydogdu
Eray Aydogdu

Reputation: 250

Did you try absolute path of your Html file ?

<script type="text/javascript">
    function myFunction() {
        $("#div1").load('~/Shared/Something/page.html');
    }
</script>

page.html must contains only html and javascript codes...

Upvotes: 0

Related Questions