ASP.NET MVC - Replace label with validation error message? - asp.net-mvc

I'd like to highlight field names instead of showing a separate error message when there is a validation error.
Is there any convenient way of doing this other than checking the ModelState Errors collection and wrapping each .LabelFor() in an if?
Also, I'd like to format labels as either bold, or add an asterisk if the model metadata has a [Required] attribute.

You'll need use a custom Object.ascx file by creating either /Shared/DisplayTemplates/Object.ascx or /Shared/EditorTemplates/Object.ascx
I can't answer any better than this guide at Brad Wilson's blog: http://bradwilson.typepad.com/blog/2009/10/aspnet-mvc-2-templates-part-4-custom-object-templates.html

Related

Umbraco Razor - binding content fields

I've created a template (View) in Umbraco (MVC) and am trying to figure out how to bind to the document type content. Keeping it really simple:
#inherits Umbraco.Web.Mvc.UmbracoTemplatePage
#{
Layout = null;
}
<h1>#Model.Title</h1>
My Umbraco document type has a Title field (alias is 'title') but if I try and run this I get build errors. I've found a whole load of documentation suggesting using a Library.NodeById() method but I believe that's for WebForms and not MVC. Can anyone offer some guidance?
You can get a property value in multiple ways with Model::
#Model.Content.GetPropertyValue("title")
#Model.Content.GetProperty("title").Value
And as a dynamic
#CurrentPage.Title
Did you remember to add your template to your document type?
You can also use the Field helper method:
#Umbraco.Field("myFieldName")
nice thing about this helper is that you can also specify alternative fields (if the first one was empty.
You can find this back in the documentation:
http://our.umbraco.org/documentation/reference/templating/Mvc/views#RenderingafieldwithUmbracoHelper

MVC Show different ValidationSummary ErrorMessage compared to ValidationMessage

In ASP.NET MVC, is it possible to show a different message in the ValidationSummary compared to what is shown in the ValidationMessage?
IE - if i have a FirstName textbox, on validation the message next to the text box will say 'You need to fill this out', but in the validation summary it will say 'Please provide a first name'.
I'm not sure if I completely understand what you are trying to accomplish, but you can specify a generic error message in the validation summary. In your view you can use:
#Html.ValidationSummary(true, "Please correct the errors below")
The boolean parameter indicates whether you want to exclude property errors. The string is the message you want displayed. Using this overload the way I have above, the model-level error message Please correct the errors below would be shown in place of the #Html.ValidationSummary() method, and the property errors would be shown where you place your #Html.ValidationMessageFor() methods.
See the MSDN documentation for a complete list of overloads.
Yes. It should be quite obvious from looking at the intellisense.
you would say:
#Html.ValidationSummary(true)
and it will contain the error messages that are located on the model or the default messages
And you can say:
#Html.ValidationMessageFor(m => m.Property, "This is a custom message")
And that overrides the message on the individual message.
Also, keep in mind that #Html.ValidationSummary(true, 'Header Message') will show your custom summary message along with the same messages that you provided in your model data annotations.
i.e. in your model class:
[Required(Message="First name is required")]
public string FirstName { get; set; }
Your validation summary would look some like this:
Header Message
First name is required
Alternatively, you can build up a custom collection of messages by using ModelState.AddModelError("Key", "Message") in your controller, then referencing that key in your view using ViewData.
After looking at the Metadata available, I don't think what I want to do is possible. What I'm going to do instead is type in the input specific value for validation, and hide the class field-validation-valid.
Providing different Errormesages beside the input fields and in the Validation Summary is not possible with #Html.ValidationSummary. Such a feature could make sense because a part of the errormessage's information can come from it's position in the page (e.g. beside a firstname input field the message could be 'Input required' and in the validation summary you need 'Input required for firstname'). Unfortunately a poor implementation for ValidationSummary in MVC, .net 2.0 provided the feature to have different messages in it's validators and in the validationsummary .

Easiest way to alter required validation message site wide

I would like to replace validation message for all model properties that have [Required] attribute from the default "The XY field is required." to "*". I want to do that site wide in one place without having to add a custom message to Required attributes or passing additional parameter to ValidationMessageFor() Html helper.
Any ideas?
See the answer to my question here :
Localizing Error Messages In ASP.NET MVC 2 (Default Validation Attributes)

ASP.NET MVC / Linq-to-SQL classes: Can I get it to infer readable display names?

If I have a table Orders with fields CustomerID, OrderID and OrderDate, then the "Linq-to-SQL classes" generated class will be called Orders, with members called CustomerID, OrderID and OrderDate. So far so good.
However, if I then do Html.LabelFor(m => m.OrderDate) then the generated text will be "OrderDate" instead of "Order Date".
I tried using Order_Date as the field name, but that didn't work. Is there any way to get it to infer a better display name?
[I know that I can use data annotations to specify the display name explicitly, but I really don't want to do that for all my classes/members - I just want it to work by convention.]
I suggest you create your own HTML Helper for this, something like Html.MyLabelFor.
The rules to apply from here are up to you. You can simply split the word by case.
There is a solution available for your requirements contained within the answer to this question. Asp.Net MVC 2 LabelFor Custom Text.
This method takes advantage of existing MVC 2 architecture to place conventions over the entire *For rendering methods instead of one off HTML helpers and without having to re-label everything with spaced property names.
How to "DRY up" C# attributes in Models and ViewModels?
Essentially what your doing is overriding the default ConventionModelMetadataProvider behavior of MVC 2 and providing hooks for you to insert your own opinionated conventions.

ASP.NET MVC - Model Validation regarding its dataType Length

I'm using ASP.NET MVC 1 on a project where I would like to validate my form submission with the ModelBinding helpers, actually I am validating it with ModelState.IsValid but it doesn't seem to consider the dataType length when validating it. For example:
I have a field nvarchar(70) called Name , but when in my form I submit a name with 200 chars, it pass the validation anyways...anyone knows how to prevent this to happen and make the modelBinding respect the datatype length?
Thanks in advance
Update: Thanks for the help till now: I'm using just standard Linq associations and modelBinding to validate the models, I hope this can help somehow
Cheers
This is a excellent comparison from the validation alternatives -so you can select what is better for you ; )
Includes concrete implementations.
I recommend you to keep your model validation logic out of the binding module. and just feed your ModelState with the validation errors from inside your service layer.
See this series from the ASP.Net MVC page for examples : )

Resources