// Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using Microsoft.Extensions.Internal;
namespace Microsoft.AspNetCore.Mvc.ModelBinding
{
///
/// Contains the result of model binding.
///
public struct ModelBindingResult : IEquatable
{
///
/// Creates a representing a failed model binding operation.
///
/// A representing a failed model binding operation.
public static ModelBindingResult Failed()
{
return new ModelBindingResult(model: null, isModelSet: false);
}
///
/// Creates a representing a successful model binding operation.
///
/// The model value. May be null.
/// A representing a successful model bind.
public static ModelBindingResult Success(object model)
{
return new ModelBindingResult( model, isModelSet: true);
}
private ModelBindingResult(object model, bool isModelSet)
{
Model = model;
IsModelSet = isModelSet;
}
///
/// Gets the model associated with this context.
///
public object Model { get; }
///
///
/// Gets a value indicating whether or not the value has been set.
///
///
/// This property can be used to distinguish between a model binder which does not find a value and
/// the case where a model binder sets the null value.
///
///
public bool IsModelSet { get; }
///
public override bool Equals(object obj)
{
var other = obj as ModelBindingResult?;
if (other == null)
{
return false;
}
else
{
return Equals(other.Value);
}
}
///
public override int GetHashCode()
{
var hashCodeCombiner = HashCodeCombiner.Start();
hashCodeCombiner.Add(IsModelSet);
hashCodeCombiner.Add(Model);
return hashCodeCombiner.CombinedHash;
}
///
public bool Equals(ModelBindingResult other)
{
return
IsModelSet == other.IsModelSet &&
object.Equals(Model, other.Model);
}
///
public override string ToString()
{
if (IsModelSet)
{
return $"Success '{Model}'";
}
else
{
return "Failed";
}
}
///
/// Compares objects for equality.
///
/// A .
/// A .
/// true if the objects are equal, otherwise false.
public static bool operator ==(ModelBindingResult x, ModelBindingResult y)
{
return x.Equals(y);
}
///
/// Compares objects for inequality.
///
/// A .
/// A .
/// true if the objects are not equal, otherwise false.
public static bool operator !=(ModelBindingResult x, ModelBindingResult y)
{
return !x.Equals(y);
}
}
}