Trapping ValidateInput - asp.net-mvc

If I have a search box on my page I clearly do not want the user to input any code that may be dangerous.
However, I have a lot of data entry pages and each one needs to have ValidateInput(false) on the controllers.
I don't want to allow dangerous input, but I also don't want to handle this in each and every controller.
Is there a way that the default, and ugly, error .Net error message can be overwritten, or is there a uniform way of handling this across controllers.
EDIT
I think maybe I didn't ask the question correctly.
For every data entry page I have I have to turn of Input Validation. This becomes somewhat boring and cumbersome. Each time I accept input I need to HTMLEncode and then HTMLDecode later.
Is there a way to do this in one central place and automatically?

About output:
Here's an interesting post.
And another one from Steve Sanderson.
I just read that post some time ago - haven't tried myself.
Give some feedback how it turns out.
About input:
you could try to mess around with model binder and HtmlEncode values it takes.

ASP.NET and MVC don't allow HTML submissions by default. You have to actively enable this. See the ValidateInputAttribute for more information.
Also, even more important than not allowing HTML input is not displaying user submitted HTML when you create output. That's why all of the default generated views use Html.Encode, and why you should, too.
Update in response to edited question
Yes, it's possible (though probably not advisable) to turn off ValidateInput globally. Make a parent controller type, and put
[ValidateInput(false)]
...on the class.
Also, I don't recommend encoding input. If you allow users to input HTML, I'd store that as-is. Your web app might not be the only thing which queries your DB! In terms of filtering out "dangerous" HTML, that's extraordinarily difficult. I'd use a tested, third-party sanitization library.

Related

How do deal with commas for input/display of large numbers?

I recall having to deal with this type of situation years ago and from what I can tell online, it really hasn't gotten any easier.
I have two possible scenarios. One, is where the user wants to see the number just input formatted with commas after exiting the input box. The other is where the user wants to actually enter the commas.
Both situations make validation and dealing with passing the data to the backend as a Decimal a bit more interesting. I realize this can be done through a variety of possibilities such as keyup/keydown/blur/focus events; modifying the jQuery validator with custom validation, etc. But this seems to imply a bunch of potential new functions and new places for things to go awry on different browsers. We've had tons of fun dealing with how these events, like blur/keyup react in different browsers and it can be a bit nightmarish.
Our current views use the HTML 5 . This facilitates validation and entry without a lot of coding. If possible, we'd like to keep using that type of input.
The user might also want to not be allowed to enter a decimal (for certain types of quantity inputs).
Also, the solution needs to work on both IE8 and Safari (for the iPad). Currently, we have a single view for all of our pages that happens to fit the iPad footprint.
Are there any elegant and simple solutions for dealing with this type of request?
Asp.Net MVC allows you to use jQuery unobtrusive validation which will take care of the heavy-lifting of cross-browser support for you.
You could decorate your view model property with a Remote attribute, which would then tell the browser validation scripts (again, without you having to write code) to call a controller/action for the field. Then, you create that controller/action and do your validation there (you can simple try to parse the number) and send back a message if things fail.
The reason I suggest this is simply for the reason that the remote validation is already a known, working thing and whatever you write on the server won't affect any client. You can be as fancy as you like in the validation without having to test JavaScript.
Here's an intro to remote validation - just don't be alarmed, there is a lot of text and the way the code is written makes it look more involved than it actually is.
Spin up a new project and you should have this going in under 15 minutes.
Best regards.
Edit
If you do want to go with a client-side solution, try something pre-built and community supported, such as autoNumeric.

ASP.NET MVC text-editor light-weight

It should be free. Easily integrable with asp.net mvc. Extremely light-weight. It must sanitize the input.
for example, say if the user enters
hhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhh
It must not break the formatting of the page!
if the user enters some nasty html or maybe any html at all or any javascript code, it should reject that.
It would be awesome if it did some sort of cuss-word checking too, but that is not a requirement.
It can be jquery based.
Before you feel tempted to mark this question as duplicate, do check whether other questions are very old or something like that.
There are lots of RTEs that can be easily integrated into an asp.net page.There are many that are jquery based. See here I use server side code to sanitize. There are a number of classes that can be used to sanitize html. Run the user entered text thru the sanitizer to strip the markup.I am using http://roberto.open-lab.com/2010/03/04/a-html-sanitizer-for-c/
Jeff Atwoods code is here
Also see this SO post

HTML Submit button vs AJAX based Post (ASP.NET MVC)

I'm after some design advice.
I'm working on an application with a fellow developer. I'm from the Webforms world and he's done a lot with jQuery and AJAX stuff. We're collaborating on a new ASP.MVC 1.0 app.
He's done some pretty amazing stuff that I'm just getting my head around, and used some 3rd party tools etc. for datagrids etc.
but...
He rarely uses Submit buttons whereas I use them most of the time. He uses a button but then attaches Javascript to it that calls an MVC action which returns a JSON object. He then parses the object to update the datagrid. I'm not sure how he deals with server-side validation - I think he adds a message property to the JSON object. A sample scenario would be to "Save" a new record that then gets added to the gridview.
The user doesn't see a postback as such, so he uses jQuery to disable the UI whilst the controller action is running.
TBH, it looks pretty cool.
However, the way I'd do it would be to use a Submit button to postback, let the ModelBinder populate a typed model class, parse that in my controller Action method, update the model (and apply any validation against the model), update it with the new record, then send it back to be rendered by the View. Unlike him, I don't return a JSON object, I let the View (and datagrid) bind to the new model data.
Both solutions "work" but we're obviously taking the application down different paths so one of us has to re-work our code... and we don't mind whose has to be done.
What I'd prefer though is that we adopt the "industry-standard" way of doing this. I'm unsure as to whether my WebForms background is influencing the fact that his way just "doesn't feel right", in that a "submit" is meant to submit data to the server.
Any advice at all please - many thanks.
The thing you need to take into consideration is how the application will work if javascript is not available. You should strive to ensure that the basic functionality works without it. This is called progressive enhancement or unobtrusive javascript and is considered a best practice.
http://en.wikipedia.org/wiki/Progressive_enhancement
The way you should do it is to use a form with a real submit button and then hijack that form to use ajax if the User Agent supports it. This is usually pretty trivial to do using the jquery forms plugin. In your action method, you can check to see if the incoming request is an ajax request by checking the Request.IsAjaxRequest property. This is set by MVC automatically on requests that have the X-Requested-With header set to XMLHttpRequest. Then you would return a full view or just some json based on that.
Here's a short screencast demonstrating this: http://www.youtube.com/watch?v=YQsFR1rkgMU&feature=player_embedded
Both solutions are viable, though using submit buttons will make your application more accessible (i.e. JavaScript will not be required in order to use it).
You could also do the both - start with a page that has all the necessary logic using postbacks, and "upgrade" it with nice AJAX-y requests and animations. This way, users with JavaScript will get the eye candy, and the page will gracefully degrade when when a user without JavaScript visits the page, falling back to the postback mechanism.

ASP.NET web forms as ASP.NET MVC

I am sorry for possible misleading about the title, but I have no idea for a proper title.
Feel free to edit.
Anyway, I am using ASP.NET Web Forms, and maybe this isn't how web forms is intended to be used, but I like to construct and populate HTML elements manually. It gives me more control.
I don't use DataBinding and that kind of stuff. I use SqlConnection, SqlCommand and SqlDataReader, set SQL string etc. and read the data from the DataReader.
Old school if you like. :)
I do create WebControls so that I don't have to copy-paste every time I need some control, but mostly, I need WebControls to render as HTML so I can append that HTML into some other function that renders the final output with the control inside.
I know I can render a control with control.RenderControl(writer), but this can only be done in (pre)Render or RenderContents overrides.
For example.
I have a dal.cs file where is stored all static functions and voids that communicate with the database.
Functions mostly return string so that it can be appended into some other function to render the final result.
The reason I am doing like this is that I want to separate the coding from the HTML as much as I can so that I don't do <% while (dataReader.Read()) %> in HTML and display the data. I moved this into a CodeBehind.
I also use this functions to render in the HttpHandler for AJAX response.
That works perfectly, but when I want to add a control (ASP.NET Server control (.cs extension, not .ascx)) I don't know how to do that, so I see my self writing the same control as function that returns string or another function inside that control that returns string and replaces a job that would RenderContents do, so that I can call that function when I need control to be appended into a another string.
I know this may not be a very good practice.
As I see all the tutorials/videos about the ASP.NET MVC, I think it suite my needs as with the MVC you have to construct everything (or most of it) by your self, which I am already doing right now with web forms.
After this long intro, I want to ask how can I build my controls so I can use them as I mentioned (return string) or I have to forget about server controls and build the controls as functions and used them that way?
Is that even possible with ASP.NET Server Controls (.cs extension) or am I right when I said that I am not using it right.
To be clear, I am talking about how to properly use a web forms, but to avoid data binders because I want to construct everything by my self (render HTML in Code Behind).
Someone might think that I am appending strings like "some " + "string", which I am not. I am using StringBuilder for that so there's no slowness.
Every opinion is welcome.
You need to stop thinking in terms of "controls" and webforms. MVC is a completely different way of constructing applications.
I also hate the automatic renderers in WebForms, they produce horrible html that never makes any sense. However, you dont want to be writing your html in your codebehind and passing it around as strings, thats just nasty. Your presentation code is mixed in with your logic, AND youre writing HTML in c# strings!!!
So, MVC... Instead of "widgets" that do interacty things with codebehinds and postbacks, yours view ONLY display data and contain forms to allow you to post to the controllers.
Because of this, you can strongly type your views to a Type, and then access the data you pass to it from a controller via the Model property. The equivalent to UserControls are Partial Views (ViewUserControl) which can be used to modularise your rendering code for types. For example, you might make an Address partial to which you pass your Person's Address property every time you need it rendered. This way you aren't repeating html all over the place.
P.S. A single file for all your DAL?
I hope I never ever have to work on an app you wrote in this manner. If your application is string-heavy then something is wrong.
Agree with #sliderhouserules, the way you are using MVC framework is awful. You must forgot all your "old school" techniques.
You should never use SqlCommands, SqlReaders, etc. in the code of the pages. You should pass to the view only a model (e.g. View(bar)) and it will be better if you avoid usage of
ViewData["some magic string"] = bar
Every time when you will use "old school" technique 2 mans and 2 cats will be killed :).
Also it's better to use some ORM (Object-Relational Mapper) like Linq2sql, NHibernate, SubSonic, etc.
If you need in samples of good application design please look at SharpArchitecture. It has a very good architecture and implementation and may help a lot. It has one sample (with Northwind db) and one more sample will be added soon.
Also look at CodeCampServer. It has very good architecture too.
It's better to look at the code of these projects instead of looking videos because existing videos can't demonstrate good sample of architecture, just a simple usage of functionality.
About server controls, you may use them if they can be used without 'runat="server"', like PlaceHolder. And you may create them too, but you shouldn't load any data in them directly. If you don't want to copy-paste html you should review your code and you should refactor it. Every duplicated code should be moved to MasterPages of UserControls (ascx ones).
And once more, please spend some time to look at these samples. You'll save your nerves and time in the future when you'll need to update the app or fix something. At the first look they can be hard to understand but this is only at the first look.
Hope this helps.
#lopkiju, I think that the MVC pattern would serve you much better than your current WebForms solution if you want that much control over the output HTML.
You can use Web Forms this way as you already do, but it is not designed to be used this way, so it will be a pain.
More detail
In my opinion, read some articles about the Separation of Concerns (also known as SoC) principle. If you apply it correctly, it can save you many-many headaches when you'll debug your app, and also for those people who you work with (eg. those who may have to read or modify your source code).
My other tip for you is this:
You are right that you shouldn't do things like <% while (dataReader.Read()) %> in your View code. But perhaps there are better ways to make it more elegant than your current way.
I think you should consider using some sort of ORM for these purposes. (LINQ to SQL, or even NHibernate.) If you get it, it will be much simpler. So much that you may not want to use DataReaders directly again. :-)
What I recommend for you
Simply, read the NerdDinner tutorial, and build the samle app by yourself step-by-step.
After that, try to build a similar app that serves a different purpose by yourself while applying the same rules and design that you applied to the tutorial.
I'm pretty sure you have the expertise to do it, and after actually doing something with it, you can pretty much get the feel of it.
The tutorial also explains and includes the principles I mentioned above, which will be very much use to you.
If you want the ASP.NET MVC path, you can set up controls as ASCX and they will simply be tags filled by the controller. It may not be old school enough for you, however.
You can create your full UI in code behind, if you so desire. This can include creating the HTML in routines.
But, I would recommend, if you are sticking with ASP.NET, reconsidering the bind model over the DataReader.Read() and output + loop. It is not only old style, it is highly inefficient and hard to maintain.
ASP.NET MVC does create a much looser ASPX, as it is just a view. And there is a much greater separation of code and UI. But it will not fit with the old school model either.
Have you considered using micro-templates? Dave Ward has a good example of of a client side data repeater that is uses micro-templates for layout after making a call to a page method. This sounds like this is more in the spirit of what you are trying to accomplish and can still be integrated nicely with WebForms.
The side effect will be that you will not rely on passing around HTML and can isolate your presentation from your logic.

How to get Model errors in AjaxSubmit?

I am using AjaxSubmit to post a form and there are server side validations done using XVal (RuleException way). I am not using the try/catch way to add error to Model and then send to view. Instead - I want to use the HandleError attibute and in the OnException I am adding the errors to Model. The major problem is how do I get those errors as a results in the Ajax Call?
There is not a great solution built in right now. Doing this correctly requires a client-side validation framework (because, to display the errors, you need to dynamically change the HTML page), and until recently, ASP.NET MVC has not had that. However, ASP.NET MVC 2 Preview 2 introduced client-side validation, so it's reasonable to presume that something might be built into the framework soon.
In the meantime, however, HandleErrorAttribute won't help you. HandleErrorAttribute only knows how to redirect to an error page, which is generally not what you want to do in response to a server-side validation error even with a "normal" POST, and certainly not with an AJAX post.
There really two different scenarios you need to handle:
Validation errors are not catastrophic failures; they are simply bad user data, which you should expect. You just need to get the information back to the page, so that the page can be marked up to tell the user how to fix their data.
You also need to handle catastrophic failures, like unanticipated exceptions. This is akin to what HandleErrorAttribute does, insofar as you can display a message to a user, but you cannot necessarily match that message up with specific fields on your page.
To handle the first scenario of error, you need to wrap the model state up into an object which will be parsable in JavaScript code; JSON is the obvious fit here. You then need to have JavaScript code on the client side which parses this object and marks up the form fields. This is easier if you tie into an existing client-side validation framework, which already contains code for marking up form fields.
To handle the second type of error, you can extend HandleErrorAttribute in order to provide JSON instead of HTML in the event of a catastrophic failure. Again, you will need to write JavaScript code that will be executed in the event of a failure -- jQuery's global ajaxError event is useful here -- that detects this structured error information you've created and display some sort of useful message to the user.
If all this sounds a bit involved, well, it is, which is why it may make more sense to wait and see what will be built-in when MVC 2 is finally released.

Resources