验证MVC核心中的非输入模型 [英] validate an non-Input model in MVC core

查看:74
本文介绍了验证MVC核心中的非输入模型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have an action-method that have an object type Input like this:

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")
            //??!??!!??!?!?!?!??!

        }
    }
}

在这种方法中,我首先将Input转换为ViewModel,然后对其进行验证.现在,我想返回在模型注释上设置的验证错误".我该怎么办?

In this method first I cast Input to my ViewModel then validate it. now I want to return my Validation Errors that I set on annotations of my model. How can I do this?

我的视图模型:

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; }
     
    }

结果:

这篇关于验证MVC核心中的非输入模型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆