Carl Carl - 24 days ago 7
C# Question

Get modelstate key for viewmodel property

I have an add product form which depends upon the user having added categories, product types etc. previously. Rather than let them complete the form, and then realise that they can't submit it, I want to show an error when the form first loads.

I want to add this error to the modelstate against the appropriate property - so my question is how can I get the modelstate key name for that property?

Code

Model.Step1.PopulateData(_productTypeSvc.GetList(), _websiteSvc.GetMaximumNumberOfProductImages(HttpContext.Request.Url.Host));
Model.Title = "Add A Product - Step 1: The Basics";
if (Model.Step1.ProductTypes.IsNullOrEmpty())
{
//Rather than string.Empty, I want to programmatically get the correct key to add the error to..
//E.g. if it were the view - HtmlHelper.NameFor(m => m.Step1.ProductTypeID)
ModelState.AddModelError(string.Empty, "Please add at least one product type before adding products.");
}


I know I can dummy the HtmlHelper object, but I'd rather avoid this and wondered if there is a better way?

Answer

Found an appropriate extension in MVC:

System.Web.Mvc.ExpressionHelper.GetExpressionText(LambdaExpression expression);

MSDN Here.

Thanks anyway guys.

Update:

public static string GetPropertyName<TModel, TValue>(this TModel model, Expression<Func<TModel, TValue>> propertySelector)
{
     return ExpressionHelper.GetExpressionText(propertySelector);
}

Then use the extension:

ModelState.AddModelError(Model.GetPropertyName(m => m.Step1.ProductTypeID), "Please add at least one product type before adding products.");