views:

10

answers:

1

Hi,

I'm using MVC 2. I have a question regarding client and server side validation. Lets say I have a class, and it has 3 properties as such:

[Required(ErrorMessage = "Required")]
public object Property1 { get; set; }

[Required(ErrorMessage = "Required")]
public object Property2 { get; set; }

[Required(ErrorMessage = "Required")]
public object Property3 { get; set; }

On my view I ONLY have Property1 and Property 2 and make them textboxes. I did not add Property3 to the view (but it is marked as required as above). If I don't type anything into the textboxes then the client side validation will fail. If I insert text into the textboxes, will client side pass even though Property3 was not set with a value? Will it then fail on the server side?

The issue that I am having is on the server side after I clicked the submit button. Here is my code for my Create action:

public ActionResult CreateApplication(Application application)
{
   try
   {
      application.ApplicationStateID = 1;
      application.SubmitterEmployeeNumber = "123456";

      if (ModelState.IsValid)
      {
         // Code here
      }
   }
   catch
   {
   }
}

ApplicationStateID and SubmitterEmployeeNumber is not set on client side (they are both marked as required), so I set it here. After I set them, why would validation still fail on the server side?

Thanks, Brendan

+1  A: 

Client side validation will pass because there's no corresponding input element to validate, server side validation will fail because you enforce a field to be required and this field value is not posted to the server. You could read this blog post to understand how model validation works and the differences between Input Validation vs Model Validation.

Darin Dimitrov
Thanks. See my updated question, maybe you can shed some more light. I will go and read that post now.
Brendan Vogt
The reason for this is because validation is performed during the model binding. You are setting the required properties **after** this model binding occurs. One possible workaround is to use the `TryUpdateModel` method instead of passing it as action argument.
Darin Dimitrov
Thanks for this Darin. Just a final question, am I doing this correct by puting everything into a try and catch? Normally in web forms I will check if the application is null like if (application == null).
Brendan Vogt
You don't need `try/catch` here especially if you are using `TryUpdateModel`. You could use `try/catch` inside the `IsValid` condition because this is where you will perform sensitive operations like trying to update database, etc...
Darin Dimitrov
So I can assume that there will be an application object passed through and it will not be null? I just don't want to try and set a property value like ApplicationStateID outside the try catch when application might passed through as null. Can it ever be passed through as null?
Brendan Vogt