logo
down
shadow

Asp.net MVC model validating


Asp.net MVC model validating

By : user2951935
Date : November 18 2020, 03:49 PM
this will help This can be done by imlementing a custom validation attribute check this link and this
Example:
code :
public sealed class DateEndAttribute : ValidationAttribute
{
    public string DateStart { get; set; }

    public override bool IsValid(object value)
    {
        // Get value of datestart property
        string dateStartString = HttpContext.Current.Request[DateStart];
        DateTime dateEnd = (DateTime)value;
        DateTime dateStart = DateTime.Parse(dateStartString);

        // Start must be before end
        return dateStart <= dateEnd;
    }

    public override string FormatErrorMessage(string name)
    {
        return name + " has to be after startdate";
    }
}
    [Required]
    [Display(Name = "StartDate")]
    public DateTime StartDate { get; set; }

    [Display(Name = "EndDate")]
    [DateEnd(DateStart = "StartDate")]
    public DateTime EndDate { get; set; }


Share : facebook icon twitter icon
Validating and ActiveRecord model based on an associated Model's data?

Validating and ActiveRecord model based on an associated Model's data?


By : Boss Ruhul
Date : March 29 2020, 07:55 AM
To fix this issue Looks like that would work just fine to me, and if you're worried about whether the edition association is defined yet, why not just add a check?
if self.edition and self.edition.communities_enabled
ASP.NET MVC 3: Validating model when information external to the model is required

ASP.NET MVC 3: Validating model when information external to the model is required


By : divivoma
Date : March 29 2020, 07:55 AM
I wish this help you Option 1 doesn't fit. The only way it would work would be to pull in the dependency via the service locator anti-pattern.
Option 2 doesn't work. Although I couldn't see how this was possible because of the C# attribute requirements, it is possible. See the following for references:
code :
public class CustomModelValidatorProvider : ModelValidatorProvider
{
    public CustomModelValidatorProvider(/* Your dependencies */) {}

    public override IEnumerable<ModelValidator> GetValidators(ModelMetadata metadata, ControllerContext context)
    {
        if (metadata.ModelType == typeof(YourModel))
        {
            yield return new YourModelValidator(...);
        }
    }
}
public class EntryRatingViewModelValidatorMvcAdapter : ModelValidator
{
    public EntryRatingViewModelValidatorMvcAdapter(
            ModelMetadata argMetadata,
            ControllerContext argContext)
                : base(argMetadata, argContext)
    {
        _validator = validator;
    }


    public override IEnumerable<ModelValidationResult> Validate(object container)
    {
        if (/* error condition */)
        {
            yield return new ModelValidationResult
              {
                MemberName = "Model.Member",
                Message = "Rating is required."
              };
        }
    }
}
Custom Model Binder Not Validating Model

Custom Model Binder Not Validating Model


By : Lithium78
Date : March 29 2020, 07:55 AM
fixed the issue. Will look into that further Description
The FromJsonAttribute only binds to the model and does, like you said, no validation.
code :
private class JsonModelBinder : IModelBinder
{
    public object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
    {
        var stringified = controllerContext.HttpContext.Request[bindingContext.ModelName];
        if (string.IsNullOrEmpty(stringified))
            return null;
        var model = serializer.Deserialize(stringified, bindingContext.ModelType);

        // DataAnnotation Validation
        var validationResult = from prop in TypeDescriptor.GetProperties(model).Cast<PropertyDescriptor>()
                                from attribute in prop.Attributes.OfType<ValidationAttribute>()
                                where !attribute.IsValid(prop.GetValue(model))
                                select new { Propertie = prop.Name, ErrorMessage = attribute.FormatErrorMessage(string.Empty) };

        // Add the ValidationResult's to the ModelState
        foreach (var validationResultItem in validationResult)
            bindingContext.ModelState.AddModelError(validationResultItem.Propertie, validationResultItem.ErrorMessage);

        return model;
    }
}
Validating a view model after custom model binding

Validating a view model after custom model binding


By : P.Chavdarov
Date : March 29 2020, 07:55 AM
To fix this issue I should have realised that I could use the ModelState.AddModelError through a custom binder, I've managed to get this working correctly now by adding the following to my custom model binder before returning the model to the controller:
code :
var validationResults = new HashSet<ValidationResult>();
var isValid = Validator.TryValidateObject(model, new ValidationContext(model, null, null), validationResults, true);
if (!isValid)
{
    foreach (var result in validationResults)
    {
        bindingContext.ModelState.AddModelError("", result.ErrorMessage);
    }
}

return model;
Model validation in ASP.NET MVC using Attributes or using IValidatableObject(sel-validating model)

Model validation in ASP.NET MVC using Attributes or using IValidatableObject(sel-validating model)


By : ahmed shaikh
Date : March 29 2020, 07:55 AM
wish of those help Use the built in Attributes in most cases. They are relatively reliable for your basic model validation and quick and easy to implement. I would only use IValidatableObject if you have some more complex custom validation that you have to implement.
Related Posts Related Posts :
  • Can we create and access a registry key in HKEY_LOCAL_MACHINE without running application with admin permissions in C#
  • Control light intensity with a UI slider
  • Threading (Does these threads exits or aborts itself?)
  • Change the function of a button if Logged in
  • how to accept value in date format in textbox in C# windows form?
  • remove the lines from RichtextBox?
  • How to call String.Split that takes string as separator?
  • Specify task timeout in parallel linq to objects
  • comparing two custom objects to prevent duplicates
  • How to Print Text from ComboBox into a MessageBox
  • How can I do a Func<object[],Expression<Func<T,bool>>> dynamic?
  • C# SqlDataReader No data exists for the row/column
  • My code is not giving the desired output
  • Is it possible to have multiple MVC routes point to the same controller/view?
  • Updating Listbox results in " Invalid cross-thread access."
  • Finding Elbow Angle with Kinect
  • Host a mvc web api application in the sub-folder of a website
  • How to generate a sequential unique id in a thread-safe way
  • How to add a separator to a WPF combobox that is databound?
  • optimize linq query with related entities
  • Optimize this code for large input
  • Is there any way to clear all list box short way?
  • ACR122 Device Programming sample does not find reader
  • Parallel Library: does a delay on one degree of parallelism delay all of them?
  • How to convert a var which contains Long to an Long[]
  • Quickly prune and create valid data combinations
  • Get 3 parameters out of a Dictionary<string, Dictionary<string Action>>
  • Regex IsMatch taking too long to execute
  • Shuffling divs using C# behindcode
  • ASP.NET Project and IE10 Compatibility Mode issues in Windows 7
  • Why can't I loop through this dictionary?
  • RavenDB Stream for Unbounded Results - Connection Resilience
  • How to remove the focus border of a CheckBox in C# Visual Studio?
  • Exception while using String.Format "Index (zero based) must be greater than or equal to zero and less than the siz
  • Caching an LDAP connection
  • C# How to detect kill event sender
  • How to Display Splashscreen and login form at same time using c#
  • Read .sql script with parameters
  • Why would I need to compile/generate methods/code at runtime?
  • Unable to create a constant value of type 'Project.Models.Subcategory'. Only primitive types or enumeration types are su
  • How to run possibly synchronous or possibly asynchronous code?
  • Drop SQLite tables using list of tables names
  • Can I organize Git submodules in a flat hierarchy?
  • How to make a server reply after receiving a request/data
  • Stored Procedure works in DB but not in C# code
  • MVVM WPF Programmatically add Child Elements
  • NCrunch and PostSharp Logging clash
  • Increasing memory usage in socket client
  • Multiple DropDownList but same action
  • How to get application memory usage as shown in Task Manager?
  • Exposing interfaces instead of concrete classes
  • How to get only postal_code data from google api?
  • Is there a way to get rid of the (by dot42) using community licence?
  • Why must I implement a function for an interface in vb.net which apparently doesn't need to be implemented in C#
  • How to remove HTML tags from the gridview Row
  • Get public post from Facebook's Graph Search API 2.x with Facebook SDK for .NET
  • C# DLL Export to Inno-Setup - Error E0434F4D
  • syntax error insert into database
  • By-pass else block of int.TryParse in Lambda Syntax
  • Retrieve "property getter" from the property name
  • shadow
    Privacy Policy - Terms - Contact Us © ourworld-yourmove.org