views:

62

answers:

3

I would like to know what is the best practice on separating the content of an aspx page (ASP.NET 3.5) from the code (I'm using C#). I have a form that users can type data in - for example they are allowed to enter a percent. If they enter data that's not valid they would get an error message:

<p class="errormsg" id="percenthigh">Please enter a percent below 100</p>
<p class="errormsg" id="percentnegative">Percent cannot be below 0</p>
<p class="errormsg" id="percentnot">This is not a percent</p>

So in essence I'm hiding the error messages and showing one depending on what the user input is.

I believe this is the best way to seperate the content from the code behind. However, how do I select elements and hide/unhide them depending on the user input? I'm aware I can do a runat="server" on the elements but the problem is that I can't select by class and am limited only to ID's.

What workarounds do you recommend? Aside from putting in the values in code behind which is notoriously difficult to debug.

Also has this been "fixed" in ASP.NET 4? And I'm interested in doing this only via C#/ASP.NET as some people have JavaScript disabled. This means that I would have to check errors on both client side and server side.

A: 

Selectionm should be by ID when you want unique elements, ID should be unique across all of your elements. Class is used like a type in HTML, and is generally used for styling.

Also, text in asp.net projects should be saved in resource files. This allows easy changing of languages.

ck
Thanks! I knew that but I guess it must have been a long day. Didn't know about the resource files, have to check that out more.
firedrawndagger
+1  A: 

You should take a look to asp net validators. In most of the cases these are good enough.

If ASP NET validators are not suitable for any reason you could check a jQuery solution like this one

In any case, I'd recommend you to avoid spending time solving problems already solved in many different (good) ways.

Claudio Redi
Fair enough, but I just don't like adding uncesssary javascript code, which I have no idea what it does - it's a black box which is something I try to avoid.
firedrawndagger
+2  A: 

Use an ASP.Net Validation control for this. That will take care of the wiring in the code for you. You use a different Validation control for each of the paragraph tags in your question.

Joel Coehoorn