Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the difference between Html.Partial and Html.Action methods?

I have a controller, action which returns PartialViewResult and view with it. For testing I output current DateTime (in action), and in view I check if it is null or not, so I know what I got.

When I try to "embed" that view in another one with Html.Action I get current datetime, so my action is called.

But when I use Html.Partial the view is rendered with null, my action method is not called. Besides, two breakpoints and debugger also confirms, in latter case the my action method is not called.

Action method:

public PartialViewResult Test()
{
  return PartialView(DateTime.Now);
}

(partial) View:

@model DateTime?

<p>@(Model ?? DateTime.MinValue)</p>

and call from main view is either @Html.Action("Test") or @Html.Partial("Test").

like image 968
greenoldman Avatar asked Nov 18 '12 18:11

greenoldman


People also ask

What is the difference between HTML partial vs HTML RenderPartial & HTML action vs HTML RenderAction?

Render vs Action partial RenderPartial will render the view on the same controller. But RenderAction will execute the action method , then builds a model and returns a view result.

What is the difference between render partial and render action?

ASP.NET MVC website describe pretty well the difference between the two. RenderPartial is used to display a reusable part of within the same controller and RenderAction render an action from any controller. They both render the Html and doesn't provide a String for output.

What is an HTML partial?

A partial view is a Razor markup file ( . cshtml ) without an @page directive that renders HTML output within another markup file's rendered output. The term partial view is used when developing either an MVC app, where markup files are called views, or a Razor Pages app, where markup files are called pages.

What is HTML render partial?

RenderPartial returns void. Html. Partial injects the html string of the partial view into the main view. Html. RenderPartial writes html in the response stream.


1 Answers

Html.Action() will call your action method, but Html.Partial() will not. Html.Partial() just renders your partial view, and is useful if you have some static content, or if you've already loaded the view data.

Html.Partial("PartialName", Model.PartialData);

Will render the PartialName view with your model data passed to it. It's a great way to break up views into clean sections, without having to incur any additional requests to the server.

Html.Action("Test")

will call your Test action, and render the result.

This is why you're seeing the NULL DateTime. Html.Action() is actually calling the action, computing the DateTime, and rendering the view, whereas Html.Partial() is only rendering the view.

like image 100
mfanto Avatar answered Oct 27 '22 12:10

mfanto