Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Html.RenderPartial() syntax with Razor

This works, because it returns the result of partial view rendering in a string:

@Html.Partial("Path/to/my/partial/view") 

But I prefer to use RenderPartial and it seems I need to write:

@{Html.RenderPartial("Path/to/my/partial/view");} 

instead of:

@Html.RenderPartial("Path/to/my/partial/view"); 

To get it to work. Error message:

 Compiler Error Message: CS1502: The best overloaded method match for 'System.Web.WebPages.WebPageExecutingBase.Write(System.Web.WebPages.HelperResult)' has some invalid arguments 

If there any better way instead of opening code block @{...} just for one method call?

like image 802
artvolk Avatar asked Aug 08 '11 10:08

artvolk


2 Answers

  • RenderPartial() is a void method that writes to the response stream. A void method, in C#, needs a ; and hence must be enclosed by { }.

  • Partial() is a method that returns an MvcHtmlString. In Razor, You can call a property or a method that returns such a string with just a @ prefix to distinguish it from plain HTML you have on the page.

like image 174
Ofer Zelig Avatar answered Nov 16 '22 01:11

Ofer Zelig


Html.RenderPartial() is a void method - you can check whether a method is a void method by placing your mouse over the call to RenderPartial in your code and you will see the text (extension) void HtmlHelper.RenderPartial...

Void methods require a semicolon at the end of the calling code.

In the Webforms view engine you would have encased your Html.RenderPartial() call within the bee stings <% %>

like so

<% Html.RenderPartial("Path/to/my/partial/view"); %> 

when you are using the Razor view engine the equivalent is

@{Html.RenderPartial("Path/to/my/partial/view");} 
like image 24
Nicholas Murray Avatar answered Nov 16 '22 02:11

Nicholas Murray