简体   繁体   English

asp.net 验证viewmodel的核心方法

[英]asp.net core method to validate the viewmodel

I have a save method which will be called via AJAX post and it passes a object instead of the view model. I parse the object and build the view model. Is there way I can validate that view model object against the data annotation defined on the view model.我有一种保存方法,该方法将通过AJAX帖子列出,并通过object而不是视图model。查看 model。

In the below example I tried to check the model state but it always is true and is not validating.在下面的示例中,我尝试检查 model state 但它始终为真且未验证。 Is there a way I can run validate against ViewModel?有什么方法可以针对 ViewModel 运行验证吗?

 public class InvoiceViewModel
    {
    
        public long InvoiceId { get; set;
    
          [Display(Name = "Invoice Number"),Required]
        public string InvoiceNumber { get; set;}
    
        [Display(Name = "Type"),Required]
        public  string InvoiceType { get; set; }
       
        [Display(Name = "Amount"),Required]
        public decimal InvoiceAmount { get; set; }
    }

   
    // controller method
    public JsonResult SaveInvoice([FromBody] object invoice)
    {
         // parse through the invoice object
         var invoiceVM = GetInvoiceViewModel(invoice)
         // I tried the ModelState.IsValid - it did nto work
         // how can I validate invoiceVM against the data annotation defined
    }

     
    public InvoiceViewModel GetInvoiceViewModel(object invoice)
    {
    }

As Camilo Terevinto said,you need to fix how to pass the model to action by ajax.正如 Camilo Terevinto 所说,您需要解决如何将 model 传递给 ajax 的操作。

Before you did the work,you need to know that if the model data you passed contains wrong format,the backend would recieve null model.For example,InvoiceAmount is a decimal type property,if you do set a string like "aaa" or an empty string " " ,it would be null.在你做之前,你需要知道如果你传递的 model 数据格式错误,后端将收到 null model。例如,InvoiceAmount 是一个小数类型的属性,如果你设置一个像"aaa"这样的字符串或者一个空字符串" " ,它将是 null。

在此处输入图像描述

And something special about model binding you need to know,the long and decimal type property have default value 0 although you do not pass the property.The Reuiqred attribute does not work for this.关于 model 绑定,您需要知道一些特殊的事情,尽管您没有传递该属性,但longdecimal类型属性的默认值为 0。Reuiqred 属性对此不起作用。

For example,you could see the following gif,I not only do not pass the value but also do not pass the InvoiceAmount property(for how to do not pass the property you could check the following code).But in the backend you could see InvoiceAmount have default value 0:例如,你可以看到下面的gif,我不仅不传递值而且不传递InvoiceAmount属性(关于如何不传递属性你可以查看下面的代码)。但是在后端你可以看到InvoiceAmount 默认值为 0:

var data = {
            InvoiceId: $("#InvoiceId").val(),
            InvoiceNumber: $("#InvoiceNumber").val(),
            InvoiceType: $("#InvoiceType").val(),
            //InvoiceAmount: $("#InvoiceAmount").val()  //remove this... 
        }

在此处输入图像描述

As a conclusion ,that is to say,for the long and decimal type property,you could not pass wrong format data to them,but you could send model without using these types' properties.综上所述,也就是说,对于longdecimal类型的属性,你不能向它们传递错误格式的数据,但你可以在不使用这些类型的属性的情况下发送 model。

Here is a whole working demo:这是一个完整的工作演示:

View:看法:

@model InvoiceViewModel
<form>
    <div>
        <label asp-for="InvoiceId"></label>
        <input asp-for="InvoiceId" class="form-control" />
    </div>
    <div>
        <label asp-for="InvoiceNumber"></label>
        <input asp-for="InvoiceNumber" class="form-control" />
    </div>
    <div>
        <label asp-for="InvoiceType"></label>
        <input asp-for="InvoiceType" class="form-control" />
    </div>
    <div>
        <label asp-for="InvoiceAmount"></label>
        <input asp-for="InvoiceAmount" class="form-control" />
    </div>
    <div>
        <input type="button" value="post" onclick="PostData()" />
    </div>
</form>
@section Scripts
{
<script>
    function PostData() {
        var data = {
            InvoiceId: $("#InvoiceId").val(),
            InvoiceNumber: $("#InvoiceNumber").val(),
            InvoiceType: $("#InvoiceType").val(),
            InvoiceAmount: $("#InvoiceAmount").val()
        }
        console.log(data);
        console.log(JSON.stringify(data));
        $.ajax({
            url: "/Home/SaveInvoice",
            type: "POST",
            contentType: "application/json; charset=utf-8",  //be sure add this...
            data: JSON.stringify(data),
            success: function (res) {
                alert(res.message);
            }
        })
    }
</script>
}

Controller: Controller:

public JsonResult SaveInvoice([FromBody]InvoiceViewModel invoice)
{
    if (ModelState.IsValid)
    {
        return Json(new { message = "Success" });
    }
    return Json(new { message = "Error" });
        
}

Result:结果: 在此处输入图像描述

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM