12

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").

1
  • Can you show us the "main view"
    – gdoron
    Nov 18, 2012 at 18:37

1 Answer 1

25

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.

4
  • 1
    Can't he call @Html.Partial("Test", new { DateTime.Now }? Aug 11, 2015 at 21:22
  • Yeah, you can do that too. You can even leave off the new {}, since DateTime is also valid as a Model. I think the question was more broadly about the difference between Html.Action and Html.Partial though, and the OP only mentioned the DateTime.Now as being for testing.
    – mfanto
    Aug 11, 2015 at 22:22
  • Do we really need to send Model.Partialdata? Main model of the page is automatically gets sent to partial views right? However if for efficiency purpose we just want to sent the particular "submodel" which is PartialData in above case then we need to use something like Model.partialData. can you kindly tell my understanding is correct or not? Jun 16, 2017 at 16:22
  • I'm not sure if the main model is automatically sent to partial views and I don't have a setup to check. But the rest of your understanding is correct. You can either pass Model, or Model.PartialData to the partial. Whatever properties you want.
    – mfanto
    Jun 17, 2017 at 5:55

Your Answer

Reminder: Answers generated by Artificial Intelligence tools are not allowed on Stack Overflow. Learn more

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.