[英]Rendering a partial view in MVC with Javascript
I've got an asp.net MVC website that consists of a topbar and a main area. 我有一个由topbar和主要区域组成的asp.net MVC网站。
Via a js function, I want to be able to retrieve new data from my Controller and display these data in the main area of my website, but without re-rendering the topbar area. 通过js函数,我希望能够从Controller检索新数据并在网站的主要区域中显示这些数据,而无需重新渲染topbar区域。
How do I do this? 我该怎么做呢?
Here is what I got: 这是我得到的:
I put the topbar and all related scripts in the _layout.cshtml
, scripts related to the mainview go to Display.cshtml
and the data itself which I want to display go inside Partial_ChartView.cshtml
我将_layout.cshtml
和所有相关脚本放在_layout.cshtml
,与主_layout.cshtml
相关的脚本转到了Display.cshtml
,而我要显示的数据本身放在Partial_ChartView.cshtml
The partial view that should display my chart data is loaded inside Display.cshtml
like this: 应该显示我的图表数据的局部视图像这样在Display.cshtml
加载:
@model MobileReports.Models.ReportViewModel
@{
ViewBag.Title = "Display";
Layout = "~/Views/Shared/_Layout.cshtml";
}
@{Html.RenderPartial("Partial_ChartView");}
The partial view Partial:ChartView.cshtml
looks like this: 局部视图Partial:ChartView.cshtml
如下所示:
@model MobileReports.Models.ReportViewModel
<div id="chartContainer">@Model.Chart</div>
The corresponding controller contains this code: 相应的控制器包含以下代码:
public ActionResult Display(Guid? id)
{
ReportViewModel viewModel = new ReportViewModel();
Guid validId = (Guid)id;
viewModel.Chart = GetChart(guid);
viewModel.ChartData = GetData(guid);
return PartialView(viewModel);
}
When I open the page at ../Report/Display , the page seems to get rendered correctly. 当我在../Report/Display中打开页面时,页面似乎正确呈现。
Now I want to add a script that calls Display(id) with a certain value. 现在,我想添加一个调用具有特定值的Display(id)的脚本。 Then I want to re-render only the main area (inside div #chartContainer) to display the new data which should now be in the model. 然后,我只想重新渲染主要区域(在div #chartContainer内部)以显示现在应该在模型中的新数据。 How do I do this? 我该怎么做呢?
Create a new method that returns a partial view containing only the data you need 创建一个新方法,该方法返回仅包含所需数据的局部视图
public ActionResult Chart(GUID id)
{
.....
return PartialView(someModel);
}
then use jquery .load
to replace the contents of your div 然后使用jquery .load
替换div的内容
$('#chartContainer').load('@Url.Action("Chart", "Report")', { id: YourGUIDValue });
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.