0

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

<div id="FilterRows">
     @{Html.RenderAction("_FilterRow");}
</div>

<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: enter image description here

Something like:

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

Is unfortunately not working. Any Ideas?

smyslov
  • 1,279
  • 1
  • 8
  • 29
  • It wouldnt work, try this http://stackoverflow.com/questions/10897433/how-to-call-html-renderaction-with-parameters-declarated-in-jscript – Dmitriy Kovalenko Jun 30 '16 at 12:07

2 Answers2

2

If you add an action which returns the partial rendered as a partial (ie. return PartialView("myView", model); then you can load using jQuery:

# Create a new element to contain...
var el  = $('<div></div>');
$('#parent').append(el);
# ...the new content
el.load('@Url.Action("action", "controller"');

(This means running the JS in the razor view to get the correct URL generation. If most of the JS is in its own file, pass the URL from a little JS in the Razor file just for things like URLs.)

Richard
  • 106,783
  • 21
  • 203
  • 265
0

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:

$("#FilterRows").append("@{Html.RenderAction("_FilterRow");}");

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

freedomn-m
  • 27,664
  • 8
  • 35
  • 57
  • Cloning was a brilliant idea! works properly for my belongings. Thanks! –  Jun 30 '16 at 12:43