简体   繁体   中英

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.

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.

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

The partial view that should display my chart data is loaded inside Display.cshtml like this:

@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:

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

Now I want to add a script that calls Display(id) with a certain value. 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. 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

$('#chartContainer').load('@Url.Action("Chart", "Report")', { id: YourGUIDValue });

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