Custom MVC Error Message Localization - asp.net-mvc

I want to localize my error messages on my model using attributes, such as RequiredAttribute and RangeAttribute. I'm using ASP.NET MVC2 in Visual Studio 2010.
This is really easy if my localized resources were in resx resource files... using ErrorMessageResourceName and ErrorMessageResourceType... however, I need to integrate it against a custom localization framework.
I have set the resourceProviderFactoryType on the globalization section in web.config, but MVC doesn't use this. It tries to access a static property on a resource file which returns the localized string.
This is the call stack...
System.ComponentModel.DataAnnotations.ValidationAttribute.SetResourceAccessorByPropertyLookup() +56576
System.ComponentModel.DataAnnotations.ValidationAttribute.SetupResourceAccessor() +146
System.ComponentModel.DataAnnotations.ValidationAttribute.get_ErrorMessageString() +12
System.ComponentModel.DataAnnotations.ValidationAttribute.FormatErrorMessage(String name) +33
System.Web.Mvc.DataAnnotationsModelValidator.get_ErrorMessage() +31
System.Web.Mvc.RequiredAttributeAdapter.GetClientValidationRules() +46
System.Web.Mvc.Html.ValidationExtensions.<ApplyFieldValidationMetadata>b__0(ModelValidator v) +10
System.Linq.<SelectManyIterator>d__14`2.MoveNext() +238
System.Web.Mvc.Html.ValidationExtensions.ApplyFieldValidationMetadata(HtmlHelper htmlHelper, ModelMetadata modelMetadata, String modelName) +207
System.Web.Mvc.Html.ValidationExtensions.ValidationMessageHelper(HtmlHelper htmlHelper, ModelMetadata modelMetadata, String expression, String validationMessage, IDictionary`2 htmlAttributes) +527
System.Web.Mvc.Html.ValidationExtensions.ValidationMessageFor(HtmlHelper`1 htmlHelper, Expression`1 expression, String validationMessage, IDictionary`2 htmlAttributes) +82
System.Web.Mvc.Html.ValidationExtensions.ValidationMessageFor(HtmlHelper`1 htmlHelper, Expression`1 expression) +75
Does anyone know if it's possible for me to somehow override how MVC retrieves the error message to display?
thanks
k

I would create a custom class attribute that inherits from the standard Mvc HandleError class attribute...
http://blog.dantup.com/2009/04/aspnet-mvc-handleerror-attribute-custom.html

Does this answer help?
How to use DataAnnotations ErrorMessageResourceName with custom Resource Solution

Related

why does AnonymousObjectToHtmlAttributes return a routevaluedictionary

Related to MVC 5.2
Whilst refactoring some code I came across the HtmlHelper method[1]:
public static RouteValueDictionary AnonymousObjectToHtmlAttributes (object htmlAttributes);
I wondered why it returned a RouteValueDictionary rather than a simpler IDictionary<string, object> which is generally used for Html Attributes.
I've assumed that this is unintentional, but wondered if I was actually missing something more profound?
[1] https://learn.microsoft.com/en-us/dotnet/api/system.web.mvc.htmlhelper.anonymousobjecttohtmlattributes?view=aspnet-mvc-5.2

pass values from other properties on my model to custom htmlhelper

I am trying to create a custom html helper that will actually have several html elements in it including an input type of file and input type of button.
I have that working fine, but I'd also like to include a few hidden inputs and populate the values of those with values from a few of the properties of my model. Is it possible to fetch the values of a few properties from my model in a custom #Html.MyCustomHelperFor(m => m.somefield)
my method signature looks like this:
public static MvcHtmlString MyCustomHelperFor<TModel, TProperty>(this HtmlHelper<TModel> htmlHelper, Expression<Func<TModel, TProperty>> expression)
also, a bit off topic, would I be better suited just writing this up in a partial view?
please advise.
You can access the full model from ViewData
MyCustomHelperFor<TModel, TProperty>(this HtmlHelper<TModel> htmlHelper, Expression<Func<TModel, TProperty>> expression)
{
MyModelClass model = htmlHelper.ViewData as MyModelClass;
string otherProperty = model.OtherProperty;
However this is not very flexible since it will only work for one model type (unless you do conditional checks (if (htmlHelper.ViewData is MyModelClass1) {..} else if (htmlHelper.ViewData is MyModelClass2) {..} etc.
I suggest you would be better of creating a partial view or custom display and editor templates.

using guid in ActionLink

I search a lot,but didn't find any solution. I have a product table and here ProductID is guid. And in index.cshtml I have a edit link
#Html.ActionLink("Edit","Edit","Admin",new{id=i.ProductID})
When I click link, url like it
http://localhost:5546/Admin/Edit?Length=5
And I get following error
The parameters dictionary contains a null entry for parameter 'id' of non-nullable type 'System.Guid' for method 'System.Web.Mvc.ActionResult Edit(System.Guid)' in 'RiotBooks.Controllers.AdminController'. An optional parameter must be a reference type, a nullable type, or be declared as an optional parameter.
Parameter name: parameters
How to I solve it?
You're using the wrong overload of ActionLink.
The one you're calling there is this one:
public static MvcHtmlString ActionLink(
this HtmlHelper htmlHelper,
string linkText,
string actionName,
Object routeValues,
Object htmlAttributes
)
but you really want to be calling this one:
public static MvcHtmlString ActionLink(
this HtmlHelper htmlHelper,
string linkText,
string actionName,
string controllerName,
Object routeValues,
Object htmlAttributes
)
So just change your call to
#Html.ActionLink("Edit","Edit","Admin",new{id=i.ProductID}, null)
and you'll be good.
For the record, the tip off to me was that ?Length=5 comes from the fact that the string "Admin" being passed into the routeValues parameter has only one property on it (Length) and the length of that string is 5.

ASP.NET MVC - pass htmlAttributes as parameter

I want to pass htmlAttributes as parameter to my HtmlHelper similar as it created in
Html.ActionLink("linktext", "Home", null, new{width="100px"})
How to pass this new{width="100px"} to my method
public static string SelectCategoryAdminWithAllItem(this HtmlHelper htmlHelper, string name, **???**)
{ }
and how to parse it?
Thanks
Always try to look at sources when interested with this kind of questions. From the implementation of HtmlHelper.TextBox
public static MvcHtmlString TextBox(this HtmlHelper htmlHelper, string name, object value, object htmlAttributes)
{
return htmlHelper.TextBox(name, value, HtmlHelper.AnonymousObjectToHtmlAttributes(htmlAttributes));
}
as you see, type of parameter is object as you cant use anonymous types as parameters to methods, and object is choice. And when parsing it, you can use HtmlHelper.AnonymousObjectToHtmlAttributes Method
I looked through the source for MVC2 when trying to figure this one out. In MVC2 they used an overload of RouteValueDictionary in System.Web.Routing to turn an object to a dictionary rather than having a helper method available like in MVC3.
public static MvcHtmlString TextBox(this HtmlHelper htmlHelper, string name, object value, object htmlAttributes)
{
return htmlHelper.TextBox(name, value, new RouteValueDictionary(htmlAttributes));
}
A bit counter intuitive but that's the standard in 2.
Edit: Updated tags to include mvc2

Anonymous type as object, how can I access a property?

I am adding some functionality to the HtmlHelper-class. Basically I want to automatically disable links on a web page based on user privileges e t c.
So I have this function:
public static string ActionLinkWithPrivileges(this HtmlHelper htmlHelper, string linkText, string actionName, object routeValues)
{
return LinkExtensions.ActionLink(htmlHelper, linkText, actionName, routeValues);
}
The problem here is the routeValues-argument. Its usually created as an anonymous type so I dont know what to cast it to. This anonymous type often has a property named "id" but just writing routeValue.id gives me a compiler error.
Any help would be appreciated!
This should work :
RouteValueDictionary routeVals = new RouteValueDictionary(routeValues);
var value = routeVals["key"];
//RouteValueDictionary is under System.Web.Routing
either implement an interface or use reflection to get the PropertyInfo and then itterate through the property collection to get the right one.
you would of course need to tell the method the name of the property to get unless it's of a particular type.

Resources