ASP.NET Core自定义绑定ModelName始终为空。
创始人
2024-11-12 04:30:12
0

ASP.NET Core中的模型绑定是将HTTP请求中的数据绑定到控制器的参数或模型对象上。有时候,可能会遇到ModelName始终为空的情况。以下是解决该问题的一种方法,包含代码示例:

  1. 创建一个自定义模型绑定器(CustomModelBinder)类,继承自IModelBinder接口:
public class CustomModelBinder : IModelBinder
{
    public Task BindModelAsync(ModelBindingContext bindingContext)
    {
        var modelName = bindingContext.FieldName; // 获取ModelName
        var valueProviderResult = bindingContext.ValueProvider.GetValue(modelName);

        if (valueProviderResult != ValueProviderResult.None)
        {
            bindingContext.ModelState.SetModelValue(modelName, valueProviderResult);

            // 执行自定义的模型绑定逻辑
            // 将数据绑定到模型对象上

            // 示例:将数据绑定到字符串属性上
            var model = new CustomModel();
            model.Name = valueProviderResult.FirstValue;
            bindingContext.Result = ModelBindingResult.Success(model);
        }

        return Task.CompletedTask;
    }
}
  1. 在模型属性上应用ModelBinderAttribute特性,指定自定义模型绑定器:
public class CustomModel
{
    [ModelBinder(BinderType = typeof(CustomModelBinder))]
    public string Name { get; set; }
}
  1. 在控制器的方法参数中使用自定义模型:
public IActionResult MyAction([Bind("Name")]CustomModel model)
{
    // 使用绑定后的CustomModel对象
    // ...
}

通过以上步骤,你可以自定义模型绑定逻辑,并确保ModelName不为空。在绑定模型时,自定义模型绑定器会被调用,并将数据绑定到模型对象的属性上。

相关内容

热门资讯

七分钟举措!pokemmo脚本... 七分钟举措!pokemmo脚本辅助(透视)竟然有辅助脚本(哔哩哔哩)1、这是跨平台的pokemmo脚...
第五分钟绝活!wepoker辅... 第五分钟绝活!wepoker辅助器软件下载(透视)其实是有辅助安装(哔哩哔哩)1、下载好wepoke...
第四分钟阶段!德州透视hhpo... 第四分钟阶段!德州透视hhpoker(透视)真是真的是有辅助下载(哔哩哔哩);1、下载好德州透视hh...
六分钟机巧!hhpoker是真... 六分钟机巧!hhpoker是真的还是假的(透视)竟然是真的有辅助透视(哔哩哔哩)六分钟机巧!hhpo...
第5分钟攻略!wepoker亲... 第5分钟攻略!wepoker亲友圈有用吗(透视)都是是有辅助神器(哔哩哔哩)第5分钟攻略!wepok...
七分钟方式!impoker辅助... 七分钟方式!impoker辅助(透视)竟然是真的有辅助辅助(哔哩哔哩)1.impoker辅助 选牌创...
第6分钟办法!we poker... 第6分钟办法!we poker插件(透视)确实是真的有辅助神器(哔哩哔哩)we poker插件脚本下...
第一分钟办法!wpk控制牌是真... 第一分钟办法!wpk控制牌是真的吗(透视)本来真的有辅助教程(哔哩哔哩)1、进入游戏-大厅左侧-新手...
三分钟方式!wpk辅助插件(透... 您好,wpk辅助插件这款游戏可以开挂的,确实是有挂的,需要了解加去威信【485275054】很多玩家...
八分钟机巧!hhpoker哪个... 八分钟机巧!hhpoker哪个俱乐部靠谱(透视)好像有辅助透视(哔哩哔哩)1、hhpoker哪个俱乐...