我的index.chtml如下
@model IEnumerable<MvcMovie.Models.Movie>
@{
ViewData["Title"] = "Index";
}
<h2>Index</h2>
<p>
<a asp-action="Create">Create New</a>
</p>
<table class="table">
<tr>
<th>
@Html.DisplayNameFor(model => model.Genre)
</th>
<th>
@Html.DisplayNameFor(model => model.Price)
</th>
<th>
@Html.DisplayNameFor(model => model.ReleaseDate)
</th>
<th>
@Html.DisplayNameFor(model => model.Title)
</th>
<th></th>
</tr>
@foreach (var item in Model) {
<tr>
<td>
@Html.DisplayFor(modelItem => item.Genre)
</td>
<td>
@Html.DisplayFor(modelItem => item.Price)
</td>
<td>
@Html.DisplayFor(modelItem => item.ReleaseDate)
</td>
<td>
@Html.DisplayFor(modelItem => item.Title)
</td>
<td>
<a asp-action="Edit" asp-route-id="@item.ID">Edit</a> |
<a asp-action="Details" asp-route-id="@item.ID">Details</a> |
<a asp-action="Delete" asp-route-id="@item.ID">Delete</a>
</td>
</tr>
}
</table>
我需要在index.html
中添加一个空的select标签帮助器<select asp-for="SimpleViewModel"></select>
SimpleViewModel
是一个ViewModel,它是
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace MvcMovie.ViewModels
{
public class SimpleViewModel
{
public string CountryCode { get; set; }
}
}
为了这样做,我需要添加 @model MvcMovie.ViewModels.SimpleViewModel位于index.chtml的顶部。当然,它不起作用,因为文件中只允许一个'model'语句
如何通过尽可能少地更改代码来解决问题?
添加电影控制器代码
// GET: Movies
public IActionResult Index(string movieGenre, string searchString)
{
var GenreQry = from m in _context.Movie
orderby m.Genre
select m.Genre;
var GenreList = new List<string>();
GenreList.AddRange(GenreQry.Distinct());
ViewData["movieGenre"] = new SelectList(GenreList);
var movies = from m in _context.Movie select m;
if (!String.IsNullOrEmpty(searchString)) {
movies = movies.Where(s => s.Title.Contains(searchString));
}
if (!string.IsNullOrEmpty(movieGenre))
{
movies = movies.Where(x => x.Genre == movieGenre);
}
return View(movies);
}
答案 0 :(得分:1)
视图只能有一个模型。目前是这样的:
@model IEnumerable<MvcMovie.Models.Movie>
因此,据推测,您当前向视图发送了IEnumerable<Movie>
。如果您不并且您只想向视图发送一个SimpleViewModel
,那么只需更改该声明:
@model MvcMovie.ViewModels.SimpleViewModel
但是,如果要将两者发送到视图,则需要将它们包装在单个视图模型中。所以你可能会创建这样的东西:
public class IndexViewModel
{
public IEnumerable<Movie> Movies { get; set; }
public SimpleViewModel IndexInfo { get; set; }
// maybe some other logic?
}
然后您可以将其用作视图模型:
@model MvcMovie.ViewModels.IndexViewModel
(相反,您可以轻松地将IEnumerable<Movie>
属性添加到SimpleViewModel
并使用它,如果结构对您正在构建的内容有意义。它对框架没有任何影响, class是一个类。)
答案 1 :(得分:0)
我看到的唯一解决方案是创建一个至少有两个属性的模型,如电影列表和简单模型列表,如下所示:
public class ComplexViewModel
{
public IEnumerable<SimpleViewModel> Simple { get; set; }
public IEnumerable<Movie> Movies { get; set; }
}
public class Movie
{
//your previous implementation
public SimpleViewModel simpleViewModel { get; set; }
}
public class SimpleViewModel
{
public string CountryCode { get; set; }
}
然后在您的视图中,您可以使用
@model MvcApplication7.ComplexViewModel
@{
ViewBag.Title = "Index";
}
<h2>Index</h2>
@Html.EditorFor(x => x.Simple);