MVC compares 2 values ​​in a model

I have an mvc application in asp.net. In my C # model, I need to compare 2 values, and then if one is bigger than the other, a message will show. Whether this is even achievable, I start on all C # mvc applications

[UIHint("ValuesModel")] public ValuesModel LowValue { get; set; } [UIHint("ValuesModel")] public ValuesModel HighValue { get; set; } 

I need to be able to set the LowValue value every time, and if in this case there is no error message, I also need to style the highest value through css after that, so I assume I can pass a class or something, so I can get accessed via javascript (I used this in php). Please help me, I'm stuck on this.

+5
source share
3 answers

You can use the very light and fairly concise ExpressiveAnnotations JS library, developed by Yaroslav Valishko. For more information, go to https://github.com/jwaliszko/ExpressiveAnnotations . This library allows you to perform various conditional checks. Like Foolproof, it is added to Visual Studio by adding the NuGet package. After adding to your model, add a using statement using ExpressiveAnnotations.Attributes; Then just use the AssertThat expression to do what you need. For instance:

 [UIHint("ValuesModel")] public ValuesModel LowValue { get; set; } [UIHint("ValuesModel")] [AssertThat("HighValue > LowValue", ErrorMessage = "Insert your error message here")] public ValuesModel HighValue { get; set; } 
+1
source

Create a folder called Infrastructure (the same level as Views, controllers, etc.).

Add New Class, LowHighCheck.cs

Use the code below to create your own validation attribute:

 using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.Linq; using System.Reflection; using System.Web; namespace YourNamespace.UI.Infrastructure { [AttributeUsage(AttributeTargets.Class, AllowMultiple = true)] public class LowHighCheck : ValidationAttribute { private string[] PropertyList { get; set; } public LowHighCheck(params string[] propertyList) { this.PropertyList = propertyList; } public override object TypeId { get { return this; } } public override bool IsValid(object value) { // integers for an example - if complex objects you'll need to // perform some more operations to compare them here int low = (int)PropertyList.GetValue(1); int high = (int)PropertyList.GetValue(2); if (high < low) { return false; } return true; } } } 

Decorate your model with the attribute:

 [LowHighCheck("LowValue", "HighValue", ErrorMessage = "your error message")] public class YourViewModel { //... } 

Remember to include the infrastructure namespace.

0
source

You can use attributes from the DataAnnotations namespace. It has a Compare attribute. Usage: [Compare("Field name to compare with", ErrorMessage = "Your Error Message")]

0
source

Source: https://habr.com/ru/post/1235175/


All Articles