我正在尝试创建一个简单的模式弹出窗口来显示新闻文章。这是在主页上。我会显示文章,如果它们超过 200 个字符,我会用一个按钮替换剩余的字符,该按钮应该显示完整文章的弹出窗口。
我正在使用 ASP.NET Core 5。
首页:
@{
ViewData["Title"] = "Home Page";
}
@model FNSDNewsViewModel
<div id="ModalPlaceHolder"></div>
<div class="text-center">
<h1 class="display-4">Welcome to the FNSD system.</h1>
<p>@DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")</p>
<h2>Latest News</h2>
<div class="news-list">
@foreach (var article in Model.NewsArticles)
{
<div class="news-article">
<h3>@article.Title</h3>
<p>@article.PublishDate.ToString("dd, MMM, yyyy")</p>
<p>
@if (article.Content.Length > 200)
{
<p>@article.Content.Substring(0, 200)...</p>
<button type="button" class="btn-sm btn-primary float-right"
data-toggle="ajax-modal" data-target="#homeNewsModal"
data-url="@Url.Action("homeNewsModal", "Home", new { id = article.Id })"
title="Click to see full news article.">
more
</button>
}
else
{
<p>@article.Content</p>
}
</div>
}
</div>
</div>
我的模态页面(
_HomeNewsModal.cshtml
):
@model FNSDNewsViewModel
<div class="modal fade" id="homeNewsModal">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<h4 class="modal-title" id="newsModalLabel">News Article</h4>
<button type="button" class="close" data-dismiss="modal">
<span>x</span>
</button>
</div>
<div class="modal-body">
<form class="form-group">
<div class="news-list">
<div class="news-article">
<h3>model.Title</h3>
<p>model.PublishDate.ToString("dd, MMM, yyyy")</p>
<p>model.Content</p>
</div>
</div>
</form>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-danger float-left" data-dismiss="modal">Cancel</button>
</div>
</div>
</div>
</div>
这是我的
HomeController
:
[HttpGet]
public IActionResult HomeNewsModal(int id)
{
FNSDNewsViewModel viewModel = _FNSDNewsControllerHelper.MapToViewModel(id).Result;
return PartialView("_HomeNewsModal", viewModel);
}
一切看起来都很好。 “更多”按钮在应该出现的时候出现。但是当你按下那个按钮时什么也没有发生。
有什么理由吗?我不明白为什么它不起作用。请感谢所有帮助。
bootstrap 模态使用 id 与按钮匹配,在您的场景中,我们使用
foreach
来渲染项目列表,以便我们也应该有多个模态内容。用我的代码如下。并在部分视图中使用 <div class="modal fade" id="[email protected]">
。
@using WebAppMvc.Controllers
@model FNSDNewsViewModel
<div id="ModalPlaceHolder"></div>
<div class="text-center">
<h1 class="display-4">Welcome to the FNSD system.</h1>
<p>@DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")</p>
<h2>Latest News</h2>
<div class="news-list">
@foreach (var article in Model.NewsArticles)
{
<div class="news-article">
<h3>@article.Title</h3>
<p>
@if (article.Content.Length > 10)
{
<p>@article.Content.Substring(0, 10)...</p>
<button type="button" class="btn-sm btn-primary float-right"
data-bs-toggle="modal" data-bs-target="#[email protected]"
@* data-url="@Url.Action("homeNewsModal", "Modal", new { id = article.Id })" *@
title="Click to see full news article.">
more
</button>
@await Html.PartialAsync("_HomeNewsModal", article)
}
else
{
<p>@article.Content</p>
}
</div>
}
</div>
</div>
这会导致页面中添加大量的html内容。这是我的测试结果。这可能不是你想要的,所以我担心你可以使用部分视图来动态显示内容。