Yggras Yggras - 1 year ago 169
jQuery Question

ASP.Net MVC 5: Html.RenderAction("...") at runtime

I want to add a PartialView multiple times by pressing a button.

<div id="FilterRows">

<button id="newRow" type="button"
class="btn btn-sm btn-default"
style="width: 50px">+</button>

This piece of code works properly. But now i want to append the div FilterRows with another PartialView of _FilterRow at clicking on the button.

This is how it looks today:

Something like:

$(document).ready(function() {
$("#newRow").click(function() {
$("#Exec").append("<br>", @{Html.RenderAction("_FilterRow");} {

Is unfortunately not working. Any Ideas?

Answer Source

As long as your script is in the page (and not in an external .js file) you can use Razor inside js (although feedback directly from MicroSoft indicates that this is "unexpected", it works fine).

Have a look at the rendered html to see what's wrong.

In this case you need quotes (") around the render action:


This assumes a number of potential issues:

  • the 'RenderAction' can't have any newlines in the output
  • the 'RenderAction' can't have any quotes in the output (either use ' on the append and " inside the render or the other-way-around)
  • the action to be rendered cannot have any row-specific parameters (which appears to be ok in this case to add a new blank row)
  • the script must be in a .cshtml file (though you can get around this by setting a global/namespace'd variable in the .cshtml and have the actual code in a .js file)
  • you need to use the correct combination of @{}/@() and render/tostring

You might be better off with @Html.RenderPartial if you just want to render some html and don't need an action.

An alternative, perhaps more friendly, mechanism would be to have the blank-row already on the page (perhaps hidden) and use .clone().