【问题标题】:Why model binding with a struct doesn't work?为什么与结构的模型绑定不起作用?
【发布时间】:2020-01-13 11:14:32
【问题描述】:

我试图了解为什么此绑定不起作用。
在我将类型从 struct 更改为 class 之前,绑定不起作用。
这是设计使然还是我遗漏了什么?

我正在使用 asp.net core 2.2 MVC

查看模型

不工作

public class SettingsUpdateModel
{
    public DeviceSettingsStruct DeviceSettings  { get; set; }
}

工作

public class SettingsUpdateModel
{
    public DeviceSettingsClass DeviceSettings  { get; set; }
}
public class DeviceSettingsClass
{
    public bool OutOfScheduleAlert { get; set; }
// other fields removed for brevity
}

public struct DeviceSettingsStruct
{
    public bool OutOfScheduleAlert { get; set; }
// other fields removed for brevity
}

控制器

[HttpPost]
public IActionResult Update(SettingsUpdateModel newSettings)
{
    // newSettings.DeviceSettings.OutOfScheduleAlert always false on struct but correct on class
    return Index(null);
}

查看

<input class="form-check-input" type="checkbox" id="out_of_schedule_checkbox" asp-for="DeviceSettings.OutOfScheduleAlert">

预期:DeviceSettings.OutOfScheduleAlert 绑定到与类相同的结构 实际:只绑定了类参数

【问题讨论】:

    标签: asp.net-core asp.net-core-mvc model-binding


    【解决方案1】:

    这是在复杂类型模型绑定中设计的。 struct 类型是一种值类型,通常用于封装一小组相关变量,例如矩形的坐标或库存中物品的特征。

    在 ComplexTypeModelBinder.cs 中,CanUpdateReadOnlyProperty 方法会将 value-type 模型的属性标记为只读,因为值类型具有按值复制的语义,这会阻止我们更新

    internal static bool CanUpdatePropertyInternal(ModelMetadata propertyMetadata)
        {
            return !propertyMetadata.IsReadOnly || CanUpdateReadOnlyProperty(propertyMetadata.ModelType);
        }
    
        private static bool CanUpdateReadOnlyProperty(Type propertyType)
        {
            // Value types have copy-by-value semantics, which prevents us from updating
            // properties that are marked readonly.
            if (propertyType.GetTypeInfo().IsValueType)
            {
                return false;
            }
    
            // Arrays are strange beasts since their contents are mutable but their sizes aren't.
            // Therefore we shouldn't even try to update these. Further reading:
            // http://blogs.msdn.com/ericlippert/archive/2008/09/22/arrays-considered-somewhat-harmful.aspx
            if (propertyType.IsArray)
            {
                return false;
            }
    
            // Special-case known immutable reference types
            if (propertyType == typeof(string))
            {
                return false;
            }
    
            return true;
        }
    

    更多详情请参考here

    BTY,如果你想绑定struct类型模型,你可以尝试使用视图的ajax请求发送json数据。

    【讨论】:

      猜你喜欢
      • 2011-12-04
      • 2021-11-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-01-11
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多