简体   繁体   English

如何将部分视图中的结果HTML插入javascript代码?

[英]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. 我在asp.net mvc Web应用程序中将网格堆栈用于拖放功能。

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". 我也有一堆MVC5部分页面(Razor),每个“小部件”一个文件。 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... 现在,这里是按钮click事件的js代码...

        $('#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. 是的,那是Razor代码与js混合在一起的。 And, unfortunately it doesn't like partialView at all, as you may have guessed. 而且,不幸的是,您可能已经猜到它根本不喜欢partialView。

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. 我试图从根本上将结果局部视图转换成字符串,以便可以在addWidget函数中使用该html字符串。 If I hardcode partialView this works and the widget is added. 如果我对partialView进行硬编码,则可以正常工作并添加了小部件。

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. 单击添加按钮后,对动作方法进行ajax调用,该方法将返回html标记,您可以根据需要将其注入DOM。

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. 现在,在您的click事件中,调用此action方法,并将响应注入到DOM中。 I do not know what your addWidget method does. 我不知道您的addWidget方法做什么。 So i commented that line out and using a generic jQuery append method call for your reference. 因此,我对此行进行了注释,并使用通用的jQuery append方法调用供您参考。

$('#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); 

         });


 });

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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