0

I am currently using ASP.net MVC (VB).

I have a model with the following property:

<Required(ErrorMessage:="Contact name is required")>
Public Property contact_name() As String

In my controller method (accepts a post request and binds various parameters to the model) I set contact_name from two other parameters :

model.contact_name = first_name + " " + last_name

I return to my view containing a form which has an input field with a value of model.contact_name and I use the tag

@Html.ValidationMessageFor(Function(model) model.contact_name

The problem is that the error message is always displayed, unless the POST request has the parameter: contact_name. Even if the error message is displayed, if I submit the form the model is valid. (modelState.isValid == true).

Since I set the value of model.contact_name and pass the model to the view, technically, the model state should be valid, the required property contact_name is not null or blank and the validationMessageFor the contact_name property should not be appearing.

Why it is appearing?
How do I stop it from appearing if the value of model.contact_name is not blank?

ZeeDawg
  • 1
  • 1
  • Because if you submit your form without a value for `contact_name`, then the `DefaultModelBinder` adds a `ModelStateError`. Just changing the value of the property does not change `ModelState` –  Jul 27 '18 at 22:29
  • Does `model.contact_name = first_name + " " + last_name` really make sense? If you are always going to put a space between those other two values then that seems to imply that they are required, so why not just put `Required` attributes on those two properties and not on `contact_name`, given that those are the ones that the user can actually affect? – jmcilhinney Jul 28 '18 at 02:16
  • By the way, you can obviously use whatever naming convention you like but, given that `ContactName` is what would be used throughout the Framework and any third-party components you may use, why use `contact_name` for a property? – jmcilhinney Jul 28 '18 at 02:17
  • @StephenMuecke when I submit the form, the contact_name has a value, the ModelState is valid, but the error message appears on the form. I ended up using javascript to add some front end validation and hid the error message if there is a value in the input field. – ZeeDawg Jul 30 '18 at 13:37
  • @jmcilhinney the parameters `first_name` and `last_name` are not always provided (not required), however if provided they should be used to populate a single field on the form. When the form is submitted, `contact_name` is required. The reason I used contact_name instead of contactName was to be consistent with the naming convention used in existing code. – ZeeDawg Jul 30 '18 at 13:42

0 Answers0