c# - 验证 MVC 核心中的非输入模型

标签 c# asp.net-mvc validation asp.net-core

我有一个具有对象类型输入的操作方法,如下所示:

public async Task<IActionResult> DoSomeThing([FromBody]object input, bool options)

{
    if (options == true)
    {
        var castedInput = (A) input;
        if (TryValidateModel(castedInput))
        {
            // do some thing
        }
        else
        {
            //return validation Errors;
            //forexample:return Error("Error1")
            //??!??!!??!?!?!?!??!
        }
    }
    else
    {
        var castedInput = (B)input;
        if (TryValidateModel(castedInput))
        {
            // do some thing
        }
        else
        {
            //return validation Errors;
            //forexample:return Error("You must fill this parameter")
            //??!??!!??!?!?!?!??!

        }
    }
}

在此方法中,我首先将输入转换为我的 ViewModel,然后验证它。现在我想返回我在模型注释上设置的验证错误。 我怎样才能做到这一点?

我的 View 模型:

public class A
{
    [Required(ErrorMessage = "Error1")]
    string Phone;
    .
    .
    .
}

public class B
{
    [Required(ErrorMessage = "You must fill this parameter")]
    string Name;
    .
    .
    .  
}

最佳答案

这是一个有效的演示:

行动:

public JsonResult DoSomeThing([FromBody]object input,bool options)

        {
            var model = new Object();
            if (options)
            {
                model = JsonConvert.DeserializeObject<A>(input.ToString());
            }
            else {
                model = JsonConvert.DeserializeObject<B>(input.ToString());
            }
            string messages = "";
            if (!TryValidateModel(model))
            {
                messages = string.Join("; ", ModelState.Values
                                 .SelectMany(x => x.Errors)
                                 .Select(x => !string.IsNullOrWhiteSpace(x.ErrorMessage) ? x.ErrorMessage : x.Exception.Message.ToString()));
            }
            return Json(messages);
        }

型号:

public class A
    {
        [Required(ErrorMessage = "Error1")]
        public string Phone { get; set; }
    }

    public class B
    {
        [Required(ErrorMessage = "You must fill this parameter")]
        public string Name { get; set; }
     
    }

结果: enter image description here

关于c# - 验证 MVC 核心中的非输入模型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63401761/

相关文章:

c# - ASP.NET MVC 4,EF5,模型中的唯一属性 - 最佳实践?

javascript - 为什么 Angular 使用的对象是未定义的?

java - 如何检查(字符串)位置是否是 Java 中的有效保存路径?

jQuery 验证,改变单独标签的颜色

C# .NET FTP 缺少依赖项?文件传输协议(protocol)

c# - 使用 TextBox 过滤 Datagridview 行

c# - Polly 如何保持重试链

c# - 将 Windows 窗体键转换为字符串

asp.net-mvc - 将 Entity Framework 与温莎城堡一起使用

jquery - 使用 asp.net mvc 自动完成下拉列表