None
None

Reputation: 5670

Get value from ModelState with key name

I am adding some error messages to my ModelState from controller so that I can display it in my view. My Code is like this.

ModelState.AddModelError(key: "MyError", errorMessage: "This phone number is already in use. Please register with a different phone number.");

And in my view I am displaying it like this

foreach (ModelState modelState in ViewData.ModelState.Values)
{     
    var errors = modelState.Errors;
    if (errors.Any())
    {
        foreach (ModelError error in errors)
        {
            <p class="common-error">@error.ErrorMessage</p>
        }
    }
}

One issue with this approach is that, it is displaying all kind of ModelState errors where I want only to show error messages with a key MyError. How can I make this?

Upvotes: 15

Views: 17525

Answers (3)

Aziz Nortozhiev
Aziz Nortozhiev

Reputation: 435

     private void SetValueFromDictionary(ModelStateDictionary modelState, shipment_view_dto model)
            {
                Type type = typeof(shipment_view_dto);
                DateTime dt;
                    foreach (var property in type.GetProperties())
                    {
                        var fieldName = $"models[0].{property.Name}";
                        if (property.Name!="created_date")
                        {
                            if (property.PropertyType == typeof(DateTime) || property.PropertyType == typeof(Nullable<DateTime>))
                            {
                                var dtString = modelState[fieldName].RawValue.ToString();
                                
                                if (!dtString.Contains("0001") && dtString.Length>=10)
                                {
                                    var dtDate = dtString.Substring(0, 10).Trim();
                                    try
                                    {
                                        dt = DateTime.ParseExact(dtDate, "MM/dd/yyyy", CultureInfo.InvariantCulture);
                                    
    
                                    }
                                    catch
                                    {
                                        dt= DateTime.ParseExact(dtDate, "M/dd/yyyy", CultureInfo.InvariantCulture);
                                    }
                                    model.SetPropValue(property.Name, dt);
                                }
                                else
                                {
                                    model.SetPropValue(property.Name, null);
                                }
                                
                            }
                            else if (property.PropertyType == typeof(double) || property.PropertyType == typeof(Nullable<double>))
                            {
                                model.SetPropValue(property.Name, double.Parse(modelState[fieldName].RawValue.ToString(), CultureInfo.InvariantCulture));
                            }
                            else if (property.PropertyType == typeof(int))
                            {
                                model.SetPropValue(property.Name, Convert.ToInt32(modelState[fieldName].RawValue));
                            }
                        }
    
                    }
            }
----
 public static Object SetPropValue(this Object obj, String name, object value)
        {
            var property = obj.GetType().GetProperty(name);
            if (property != null)
            {
                property.SetValue(obj, value, null);
            }
            return obj;
        }
----
 SetValueFromDictionary(ModelState, shipment);

Upvotes: 0

Mihail Stancescu
Mihail Stancescu

Reputation: 4138

You can add a @Html.ValidationSummary(true, "", new { @class = "some_error_class" }) to show the validations messages from the model state automatically.

You can add it just after the @Html.BeginForm({...}) { call, wrapped in a div.

The true parameter will show the control errors as well, set it to false to show only errors defined like this: ModelState.AddModelError("", "My custom error message");

Upvotes: 0

j.v.
j.v.

Reputation: 997

You can iterate through keys like this:

foreach (var modelStateKey in ViewData.ModelState.Keys)
{
    //decide if you want to show it or not...
    //...

    var value = ViewData.ModelState[modelStateKey];
    foreach (var error in value.Errors)
    {
        //present it
        //...
    }
}

Upvotes: 21

Related Questions