简体   繁体   中英

How to insert resulting HTML from a partial view into javascript code?

I am using grid-stack for drag/drop functionality in my asp.net mvc web application.

I have an "Add Widget" button....

<button class="btn btn-white btn-primary" id="addwidget" type="submit">Add Widget</button>

I also have a bunch of MVC5 partial pages (Razor), one file for each "widget". When I click the "Add Widget" button I want to insert a widget onto the page. Right now here is the js code for the click event of the button...

        $('#addwidget')
        .click(function () {
            var grid = $('.grid-stack').data('gridstack');
            var partialView = @Html.Partial("~/Views/Widgets/_MyImportLatest.cshtml").ToHtmlString();
            grid.addWidget($('<div class="ibox-content" style="height:160px;">' + partialView + '</div>'), 0, 0, 3, 2, true);
        });

Yes, that's Razor code mixed in with js. And, unfortunately it doesn't like partialView at all, as you may have guessed.

I'm trying to basically get the resulting partial view into a string so that I can use that html string in the addWidget function. If I hardcode partialView this works and the widget is added.

Any ideas? Thanks!

You may consider getting the partial view content via an action method asynchronously as needed. When your add button is clicked, make an ajax call to the action method which will return the html markup and you may inject that to the DOM as needed.

public ActionResult GetWidget()
{
  return PartialView("~/Views/Widgets/_MyImportLatest.cshtml")
}

Now in your click event, make a call to this action method and inject the response coming back to the DOM. I do not know what your addWidget method does. So i commented that line out and using a generic jQuery append method call for your reference.

$('#addwidget').click(function () {

        var grid = $('.grid-stack').data('gridstack');
        $.get("/YourControllerName/GetWidget",function(htmlResponse){

            $("#YourContainerDiv").append(htmlResponse);
            // grid.addWidget($('<div>' + htmlResponse + '</div>'), 0, 0, 3, 2, true); 

         });


 });

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