【发布时间】:2019-11-27 17:06:44
【问题描述】:
很抱歉打扰简单的事情,但我真的找不到解决这个问题的方法。
我正在构建一个 Gallery,其中包含不同的字段,其中之一是 Category。
类别类是一个公共枚举,我想检索数据库中的所有图像并根据我的类别选择将它们显示在视图中。
在这里你可以找到我到目前为止写的代码。
查看:
<form method="get" asp-controller="Gallery" asp-action="index">
<div style="height:60px;" class="container">
<div class="row">
<div class="col-md-5">
<div class="row" style="padding-top:10px;">
<div class="col-md-5">
@Html.Editor("Name", new { htmlAttributes = new { @class = "form-control", placeholder = "Name..." } })
</div>
</div>
</div>
<div class="col-md-5">
<select class="custom-select form-control mr-sm-2" asp-items="Html.GetEnumSelectList<Category>()"></select>
</div>
<div class="col-md-1">
<div class="row" style="padding-top:10px; padding-right:20px;">
<button type="submit" name="submit" class="btn btn-success form-control" value="submit">
<i class="fas fa-search fa-1x"></i>
</button>
</div>
</div>
</div>
</div>
</form>
控制器:
public IActionResult Index(string Name, Category category)
{
var model = _galleryRepository.GetAllImages();
StringBuilder param = new StringBuilder();
param.Append("&Name=");
if (Name != null)
{
param.Append(Name);
}
if(Name != null)
{
model = _galleryRepository.SearchName(Name);
}
if(category != Category.All)
{
model = _galleryRepository.SearchCategory(category);
}
return View(model);
}
型号分类:
public enum Category
{
All,
Photography,
Portrait,
Nature
}
模型库:
public class Gallery
{
public int Id { get; set; }
public int Like { get; set; }
public string Comment { get; set; }
[Required]
[MaxLength(40, ErrorMessage ="Name cannot exceed 40 characters")]
public string Name { get; set; }
[Required]
[MaxLength(100, ErrorMessage = "Description cannot exceed 100 characters")]
public string Description { get; set; }
[Required]
public Category Category { get; set; }
public string PhotoPath { get; set; }
}
我根据图像名称创建了一个搜索表单,它工作得很好。但是当基于类别选择检索图像时,它不起作用。 我在与类别相关的 If 语句上的 Controller 上使用了断点,我意识到条件会触发,但里面的模型没有。
因此,我在第一次使用 Enum 并基于 Enum 类检索数据时,向专家询问如何修复它。
非常感谢您的帮助,我希望我能弄清楚我的问题。
【问题讨论】:
-
我将首先让您的
<select>具有asp-for="Category"属性。这将为其提供正确的name属性,以便在您发布您的值时进行模型绑定(它还将在回发后保留用户选择的值)。您可能还必须将控制器操作参数从category更新为Category
标签: asp.net-mvc asp.net-core asp.net-core-tag-helpers