【发布时间】:2021-06-11 11:26:01
【问题描述】:
我有一个使用两个 ViewComponents 的视图。一个在页面通过 ajax 调用加载时呈现,另一个在单击事件上加载。目前,呈现第二个 ViewComponent 的锚标记只是呈现它并停留在那里。我想更改行为,以便锚标记文本更改为“隐藏预测”并在点击时隐藏预测组件。
我尝试使用 ViewData 来完成此操作,但我被绊倒了,我想是因为我将 ViewData 传递给呈现 ViewComponent 的操作,然后主视图无法访问 ViewData?有什么方法可以通过我当前设置的代码来完成此任务?
查看
@model OpenWeather.Models.CityViewModel
@{
ViewData["Title"] = Model.Name;
}
<!--First ViewComponent, rendered with ajax on load-->
<div id="current-weather">
</div>
<a id="forecast-link" asp-action="Forecast" asp-route-lon="@(Model.Coord.lon)" asp-route-lat="@(Model.Coord.lat)">Get Five-Day Forecast</a>
<!--Second ViewComponent, rendered on above anchor tag click-->
<div id="forecast">
</div>
<script src="~/lib/jquery/dist/jquery.min.js"></script>
<script>
$(document).ready(function (e) {
var params = window.location.pathname.split("/")
$("#current-weather").load("/Home/CurrentWeather?id=" + params[3]);
$("#forecast-link").click(function (e) {
e.preventDefault();
var params = window.location.pathname.split("/");
$("#forecast").load($(this).attr('href'));
$(this).hide();
});
});
</script>
控制器操作
public IActionResult City(double id)
{
var city = _openWeatherService.GetCity(id);
return View("City", new CityViewModel(city));
}
public IActionResult CurrentWeather(double id)
{
return ViewComponent("CurrentWeather", new { id = id });
}
public IActionResult Forecast(double lat, double lon)
{
return ViewComponent("Forecast", new { lat = lat, lon = lon });
}
CurrentWeather 视图组件
@model OpenWeather.Models.CurrentWeatherViewModel
<h3>@Html.DisplayFor(model => model.Time)</h3>
<div id="current-weather-summary">
<div id="current-weather-summary-panel-one">
<h3>@Html.DisplayFor(model => model.Temp)°</h3>
<img src="http://openweathermap.org/img/w/@(Model.Icon).png" />
<h5>@Html.DisplayFor(model => model.Description)</h5>
</div>
<div id="current-weather-summary-panel-two">
<dl>
<dt>@Html.DisplayNameFor(model => model.High)</dt>
<dd>@Html.DisplayFor(model => model.High)°</dd>
<dt>@Html.DisplayNameFor(model => model.Low)</dt>
<dd>@Html.DisplayFor(model => model.Low)°</dd>
<dt>@Html.DisplayNameFor(model => model.Sunrise)</dt>
<dd>@Html.DisplayFor(model => model.Sunrise)</dd>
<dt>@Html.DisplayNameFor(model => model.Sunset)</dt>
<dd>@Html.DisplayFor(model => model.Sunset)</dd>
</dl>
</div>
</div>
预测视图组件
@model OpenWeather.Models.ForecastViewModel
@{
foreach (var x in Model.ForecastDays.AsEnumerable())
{
<div class="forecast-day">
<h5>@x.Time</h5>
<p>@x.Description.</p>
<img src="http://openweathermap.org/img/w/@(x.Icon).png" />
<p>Day: @x.TempDay° | Night: @x.TempNight°</p>
</div>
}
}
【问题讨论】:
标签: jquery asp.net-core asp.net-core-viewcomponent