我使用位于此处的示例代码:http://code.msdn.microsoft.com/MVC5-Demo-with-Entity-c6bc81df
基本上,这是电影数据库的 CRUD 示例,您可以在其中创建、读取、更新和删除它们。
我的问题是:单击同一页面上的详细信息
链接时如何显示所选电影的详细信息?
此时,单击详细信息时,您将被重定向到将显示有关该电影的信息的 Controller 和操作。
我可以在列出电影的同一页面上显示详细信息吗?
最佳答案
有多种方法可以做到这一点,但它们都归结为进行某种 Ajax 调用来加载部分 View 。以下是一个有效的实现,尽管是最小的:
模型 - Movie.cs
public class Movie
{
public int ID { get; set; }
public string Title { get; set; }
public DateTime ReleaseDate { get; set; }
public string Genre { get; set; }
public decimal Price { get; set; }
}
我在这里推荐一个 View 模型,但这似乎有点超出了当前问题的范围。
Controller - MoviesController.cs
public class MoviesController : Controller
{
private readonly List<Movie> movies = new List<Movie>
{
new Movie { Title = "SomeTitle", Price = 23.25M, ID = 1 },
new Movie { Title = "AnotherTitle", Price = 123.25M, ID = 2 }
};
public ActionResult Index()
{
return this.View(this.movies);
}
public PartialViewResult Details(int id)
{
return this.PartialView("_details", this.movies.First(x => x.ID == id));
}
}
部分 View - _Details.cshtml
@model YourProject.Models.Movie
<hr/>
<h3>Details</h3>
@Html.DisplayFor(m => m.Title)
@Html.DisplayFor(m => m.Price)
...etc
<button type="button" id="clearDetails">Details</button>
主视图 - Index.cshtml
@model IEnumerable<YourProject.Models.Movie>
<script src="http://code.jquery.com/jquery-2.1.1.min.js"></script>
<script type="text/javascript">
$(function () {
var detailsPartial = $('#details');
$('.details-link').click(function (event) {
event.preventDefault();
var url = $(this).attr('href');
$.ajax({
url: url,
type: 'get',
success: function(data) {
detailsPartial.html(data);
$('#clearDetails').click(function () {
detailsPartial.html(null);
});
}
});
});
});
</script>
<h2>Movies</h2>
<table>
<thead>
<tr>
<th></th>
<th>@Html.DisplayNameFor(x => x.Title)</th>
<th>@Html.DisplayNameFor(x => x.Price)</th>
</tr>
</thead>
<tbody>
@foreach (var movie in Model)
{
<tr>
<td>@Html.ActionLink("Details", "Details", new { id = movie.ID }, new { @class = "details-link" })</td>
<td>@Html.DisplayFor(x => movie.Title)</td>
<td>@Html.DisplayFor(x => movie.Price)</td>
</tr>
}
</tbody>
</table>
<div id="details"></div>
将这些放在一起,您将得到一个 View ,其中可以单击详细信息,Ajax 将从服务器检索部分 View HTML 并将其插入到指定的 div 标记中。
关于asp.net-mvc-5 - MVC 5 - 选择项目时在同一页面中显示项目详细信息,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24896507/