DefaultModelBinder बढ़ा कर अपनी खुद की ModelBinder करें:
public class LocalizationModelBinder : DefaultModelBinder
अवहेलना SetProperty:
base.SetProperty(controllerContext, bindingContext, propertyDescriptor, value);
foreach (var error in bindingContext.ModelState[propertyDescriptor.Name].Errors.
Where(e => IsFormatException(e.Exception)))
{
if (propertyDescriptor.Attributes[typeof(TypeErrorMessageAttribute)] != null)
{
string errorMessage =
((TypeErrorMessageAttribute)propertyDescriptor.Attributes[typeof(TypeErrorMessageAttribute)]).GetErrorMessage();
bindingContext.ModelState[propertyDescriptor.Name].Errors.Remove(error);
bindingContext.ModelState[propertyDescriptor.Name].Errors.Add(errorMessage);
break;
}
}
जाँच करने के लिए समारोह bool IsFormatException(Exception e)
जोड़ें यदि एक अपवाद एक FormatException है:
[AttributeUsage(AttributeTargets.All, Inherited = false, AllowMultiple = false)]
public class TypeErrorMessageAttribute : Attribute
{
public string ErrorMessage { get; set; }
public string ErrorMessageResourceName { get; set; }
public Type ErrorMessageResourceType { get; set; }
public TypeErrorMessageAttribute()
{
}
public string GetErrorMessage()
{
PropertyInfo prop = ErrorMessageResourceType.GetProperty(ErrorMessageResourceName);
return prop.GetValue(null, null).ToString();
}
}
को विशेषता जोड़ें:
if (e == null)
return false;
else if (e is FormatException)
return true;
else
return IsFormatException(e.InnerException);
एक गुण कक्षा बनाएं वह संपत्ति जिसे आप सत्यापित करना चाहते हैं:
[TypeErrorMessage(ErrorMessageResourceName = "IsGoodType", ErrorMessageResourceType = typeof(AddLang))]
public bool IsGood { get; set; }
AddLang एक resx फ़ाइल है और IsGoodType संसाधन का नाम है।
और अंत में Global.asax.cs Application_Start में जोड़ें:
ModelBinders.Binders.DefaultBinder = new LocalizationModelBinder();
चीयर्स!
स्रोत
2010-04-23 13:29:12
मुझे ModelState.AddModelError() के बारे में पता है, लेकिन UpdateModel() स्वचालित रूप से त्रुटि संग्रह में मान जोड़ता है। जब तक मैं आपके उत्तर को गलत समझ नहीं पा रहा हूं? –
ठीक है जब आप मान्य करते हैं, मॉडलस्टेट में कुछ जोड़ें। यहां एक महान ट्यूटोरियल है। http://blog.maartenballiauw.be/post/2008/08/29/Form- validation-with-ASPNET-MVC-preview-5.aspx –
मैं उम्मीद कर रहा था कि मुझे सबकुछ बांधना न पड़े, लेकिन हो सकता है कि एकमात्र तरीका अगर मैं अपने संदेश चाहता हूं? –