首页 > 解决方案 > 从下拉列表中获取价值以在 asp.net 核心中建模

问题描述

我有一个带有 EntityFramework Core 的 .NET 5 应用程序,我尝试从下拉列表中链接实体的类型:

我有商务舱

public class Bar : IdEntity
{
    public BarType BarType { get; set; }
    
    
public class BarType : IdEntity
{
    public int Id { get; set; }
    public string Name { get; set; }

为了不直接Bar在视图中使用,我创建了一个 DTO(数据传输对象,或者只是一个 viewModel),如下所示:

public class BarDTO : IdEntityDTO
{
    public int BarTypeId { get; set; }
    public BarType BarType { get; set; }

在控制器中我做:

public class BarController : IdEntityController<Bar, BarDTO>
{
    public override async Task<IActionResult> CreateAsync()
    {
        var barTypes=await _repository.ListAsync<BarType>();
        ViewBag.BarTypes = barTypes;
        return await base.CreateAsync();
    }

在视图中

@model MyApp.Web.ViewModels.BarDTO

<select asp-for="BarTypeId" 
        asp-items="@(new SelectList(ViewBag.BarTypes, 
                                            "Id", "Name"))">
    <option value="">please select</option>
</select>

我的问题是如何将选择用户选项与BarTypeof链接,Bar以在数据库中创建一个Bar具有相应类型 ID 的有效用户。

标签: c#.netasp.net-coredrop-down-menu.net-5

解决方案


model binding你的问题涉及到asp.net core中所谓的。更具体地说,您希望将 intId转换为BarType. 从客户端发送的form数据只是与相应键配对的字符串值。键就像指向相应模型属性的路径一样。因为服务器端的模型可能是具有深层属性图的复杂类型。所以key可以是一个长点分隔的路径。在您的情况下,您的路径BarType基本上是针对错误的对应Id. 模型绑定器不能简单地将 转换int为 的实例BarType。正确的路径是BarType.Id。所以你可以有这样的代码:

<select asp-for="BarType.Id" asp-items="@(new SelectList(ViewBag.BarTypes, "Id", "Name"))">
    <option value="">please select</option>
</select> 

这将帮助模型绑定器BarType使用收到的Id. 然而,我们只是发送了,所以只有theId的实例和所有的s 都是空的。html 元素只能保存一个映射到一个属性的值,通常这就是键值。在您的情况下,模型实际上根本不需要。当我们处理可选择的数据时,我们只需要选择的 key/id。考虑到这一点,我们完成了上面的代码。BarTypeIdNameSelectBarType.Name

如果您也想收到BarType.Name,我必须说它设计错误。除非BarType.Name可以编辑从客户端发送的消息,但在这种情况下,它显然只是一个常量,例如BarType.Id. 保存数据时,Id我们需要链接实体(建立关系),其他属性根本不重要,实际上可以从Id.

如果您仍然想收到BarType.Name无论如何,您至少有 2 个选项。第一个简单的方法是声明一个包含Idand的非映射属性Name,以某种方式构造计算值,以便您可以从中提取每个单独的值。这是一个例子:

public class BarType : IdEntity
{
  public int Id { get; set; }
  public string Name { get; set; }
  //this property should be configured as not-mapped (ignored)
  public string Id_Name {
     get {
        if(_id_Name == null){
            _id_Name = $"{Id}_{Name}";
        }
        return _id_Name;
     }
     set {
        _id_Name = value;
     }
  }
  string _id_Name;
  
  //a method to parse back the Id & Name
  public BarType ParseIdName(){
      if(!string.IsNullOrWhiteSpace(Id_Name)){
          var parts = Id_Name.Split(new[] {'_'}, 2);
          Id = int.TryParse(parts[0], out var id) ? id : 0;
          Name = parts.Length > 1 ? parts[1] : null;
      }
      return this;
  }
}

现在Id,您可以使用:而不是使用选定的值Id_Name

<select asp-for="BarType.Id_Name" asp-items="@(new SelectList(ViewBag.BarTypes, "Id_Name", "Name"))">
        <option value="">please select</option>
</select>

请注意,在BarType控制器操作中实际使用模型中可用的绑定之前,您需要手动调用该方法BarType.ParseIdName,如下所示:

public override Task<IActionResult> Create(Bar entity) 
{
    entity.BarType?.ParseIdName();
    //the entity is ready now ...
    //...
    return base.Create(entity);
}

第一个选项很简单,但有点棘手,我不会亲自使用它。更标准的方法是使用带有 custom 的第二个选项IModelBinder。这以模型类型为目标BarType并将 解析Id为 的实例BarType。这个解决过程应该很快。

public class BarTypeModelBinder : IModelBinder {
     public Task BindModelAsync(ModelBindingContext bindingContext)
    {
        var fieldValue = bindingContext.ValueProvider.GetValue(bindingContext.FieldName).FirstValue;
        //here we just instantiate an instance of BarType with Id but without Name
        if(int.TryParse(fieldValue, out var id)){
          bindingContext.Result = ModelBindingResult.Succeed(new BarType { Id = id });
        }
        else {
          bindingContext.Result = ModelBindingResult.Failed();
        }         
        return Task.CompletedTask;
    }
}

您应该像这样使用该模型绑定器:

[ModelBinder(typeof(BarTypeModelBinder))]
public class BarType : IdEntity
{
   //...
}

这几乎完成了。现在谈谈你如何BarType从它的Id. 正如我所说,通常我们只需要Id创建一个BarType仅包含 Id 的实例(如上面的代码所示)就足够了。这当然非常快。如果您也需要Name,您可能必须解决BarType使用某些服务的实例。因为它需要快速,所以您确实需要某种in-memory查找(或缓存数据)。假设您有一个服务来解析一个BarType实例,Id如下所示:

public interface IBarTypeService {
   BarType GetBarType(int id);
}

您可以像这样使用该服务BarTypeModelBinder

if(int.TryParse(fieldValue, out var id)){
   var barType = _barTypeService.GetBarType(id);
   bindingContext.Result = ModelBindingResult.Succeed(barType);
}
else {
   bindingContext.Result = ModelBindingResult.Failed();
}

对于初学者来说,第二个选项可能有点复杂(因为它涉及一个很好IBarTypeService的缓存支持,或者至少是一个很好的方式来提供一些内存中的数据查找),但它确实是标准的方式。一旦你熟悉了这个逻辑,就会感觉很正常。


推荐阅读