简体   繁体   中英

ASP.Net MVC 5: Html.RenderAction(“…”) at runtime

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: 在此处输入图片说明

Something like:

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

Is unfortunately not working. Any Ideas?

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM