简体   繁体   English

如何将部分视图放入JavaScript中的div(使用jQuery)

[英]How to put a Partial View into a div in JavaScript (with jQuery)

I have ,MyPartialView.cshtml': 我有MyPartialView.cshtml':

<div id="partialDiv">some content</div> 

an 'index.cshtml': 'index.cshtml':

<div id="mainDiv"> </div>

and an 'index.js'. 和一个“ index.js”。

The 'index.js' should do sth like: 'index.js'应该像这样:

$('mainDiv').html($('#partialDiv'))

to put the partial view into the main div . 将部分视图放入主div

(writing @<text> <div> @Html.Partial("MyPartialView")</div></text>) in my .cshtml works, but I need to change the content dynamically. (在.cshtml中工作(写@<text> <div> @Html.Partial("MyPartialView")</div></text>) ,但是我需要动态更改内容。 Therefore, I thought maybe there is an equivalent in JavaScript for ' Html.Partial ' 因此,我以为JavaScript中的' Html.Partial '可能等效

(Or is there another way to get a Partial View without an AJAX Call) (或者还有另一种方法可以在不进行AJAX调用的情况下获取部分视图)

cshtml files are rendred in server side. cshtml文件在服务器端解析。 you can't load it using just JavaScript. 您不能仅使用JavaScript加载它。 the perfect way is using Ajax by calling an Action that return your partial view 完美的方法是通过调用返回部分视图的Action使用Ajax

@Html.Partial("MyPartialView") used only to render single partial view file (also with @Html.RenderPartial() ). @Html.Partial("MyPartialView")仅用于呈现单个局部视图文件(也用于@Html.RenderPartial() )。 You can use AJAX to call controller action which returns partial view: 您可以使用AJAX调用控制器操作,该操作将返回部分视图:

AJAX Request AJAX请求

$.ajax({
    type: 'GET',
    url: '@Url.Action("ActionName", "ControllerName")',
    // other settings
    success: function (result) {
        $('mainDiv').html(result);
    }
});

Controller Action 控制器动作

[HttpGet]
public ActionResult ActionName()
{
    // do something
    return PartialView("MyPartialView");
}

Note that there's no equivalent of calling partial view in JS, because you need to make request to server which can't be simply handled by standard JS functions. 请注意,在JS中没有等效的调用部分视图的方法,因为您需要向服务器发出请求,而这是标准JS函数无法简单处理的。

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

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