Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
492 views
in Technique[技术] by (71.8m points)

c# - ValidationMessageFor together with AddModelError(key, message). What's the key?

I am developing a client-side and server-side validation for a certain viewModel property.

In the .cshtml file I put this:

@Html.DropDownListFor(model => model.EntityType.ParentId, Model.ParentTypeList, "")
@Html.ValidationMessageFor(model => model.EntityType.ParentId)

In the Controller for the business validation

catch (BusinessException e)
{
    ModelState.AddModelError("EntityType.ParentId", Messages.CircularReference);
}

The above works as expected: if an exception is caught, the message appears next to the dropdownlist.

However, I find that this way is not very elegant. In the cshtml, I use a method to generate all the required information about the validation. In the controller, I must know the exact Key string and use it.

Isn't there a better way of doing this?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You could write an extension method that will take a lambda expression for the key instead of a string:

public static class ModelStateExtensions
{
    public static void AddModelError<TModel, TProperty>(
        this ModelStateDictionary modelState, 
        Expression<Func<TModel, TProperty>> ex, 
        string message
    )
    {
        var key = ExpressionHelper.GetExpressionText(ex);
        modelState.AddModelError(key, message);
    }
}

and then use this method:

catch (BusinessException e)
{
    ModelState.AddModelError<MyViewModel, int>(
        x => x.EntityType.ParentId, 
        Messages.CircularReference
    );
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...