为什么模型与结构的绑定不起作用?

Why model binding with a struct doesn't work?

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

我正在使用 asp.net 核心 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 绑定到与 class 相同的结构 实际:只有 class 参数被绑定

它是在复杂类型模型绑定中设计的。 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,如果你想绑定结构类型模型,你可以尝试使用来自视图的 ajax 请求发送 json 数据。