How to validate controls inside editform template of ASPxGridView? - devexpress

I have an ASPxGridView with edit form template and some bound controls inside. After update I want to validate, check the values in controls on server side. As far as I could find this is not possible. DevExpress recommends subscribing to the RowUpdating event, but this is plain wrong. Useless as is very much of their so called support.
The problem is, that if controls contains some invalid text and it raises an exception somewhere long before RowUpdating and it gets eaten by devexpress. All it comes back to client is some message like "Input string was not in a correct format".
I want to validate input controls on the server side.
And yes, I do row validating also, but this is useful only for validating business logic.
So, how to validate controls that are bound inside EditForm template on server side?

Could you please clarify? You want to validate the values after you update or actually before you write the values to the database or each control individually as it loses focus before you can initiate the update? If it is necessary to do server side validation then I would recommend doing it in the RowUpdating and RowInserting server side event handlers as was recommended by DevExpress. Why do you think this is wrong? You can validate each of the bound controls' values in the e.NewValues collection of grid's Updating and Inserting events. If any of the values do not pass validation you can cancel the update/insert action. Could you outline your desired workflow in a little more detail?
A previous poster said a hack was necessary, putting a container inside the edit form template, which is not true. You can use the edit form template itself via the .NamingContainer of any control in the edit form template. Put your validation routine in the server side _Validation event handler of the specific controls.
You can evaluate the template controls as a group:
EditFormValid = ASPxEdit
.AreEditorsValid(myGrid.FindEditFormTemplateControl("myControl")
.NamingContainer);
Or you can update a class variable during each control's validation routine
public class foo
{
bool EditFormValid = true;
.
.
.
void myControl_Validation(object sender, ValidationEventArgs e)
{
EditFormValid = EditFormValid && myControl.IsValid;
}
void myGrid_RowUpdating(object sender, ASPxDataUpdatingEventArgs e)
{
If(EditFormValid)
{
.
.
.
}
else e.Cancel = true;
}
}
I have found DevExpress extremely effective and flexible. However the flexibility can be a double edge sword as there are many ways to almost do everything you need most of the time but usually one way to do everything you need all of the time. A developer can easily build on top of what works in one instance but isn't necessarily right/best practice and get to a point where they have coded into a corner as they continue to build upon a project.
If you can provide more specifics, so can I.

As far as I know this is not possible to do. Devexpress controls leave a lot to wish for. There is no way to check if validation was successful. Clearly a big issue.
What you can do is to run validation again with ASPxEdit.AreEditorsValid(). But for this you would have to do a little hack (as always with devexpress).
Put a container inside your edit form, a simple div with runat="server" and ID would do. This is your container.
Than get his div with FindEditFormTemplate() and use it in ASPxEdit.AreDitorsValid().
This workaround has drawbacks:
clutters your aspx code with unnecessary elements
page execution on server side is slower
page rendering on browser side is slower
ValidateEditorsIncontainer() runs validation again so there is a big
performance hit
All of the above are trademarks of DevExpress controls. But look at it from the bright side. Their grid sometimes takes up to five unnnecesary server and database roundtrips just to start editing.

Related

How to register the client side added data for postback validation on server side?

If I add Items to a Select element at the client side and then submit the form, I get the following error:-
Invalid postback or callback argument. Event validation is enabled using in configuration or <%# Page EnableEventValidation="true" %> in a page. For security purposes, this feature verifies that arguments to postback or callback events originate from the server control that originally rendered them. If the data is valid and expected, use the ClientScriptManager.RegisterForEventValidation method in order to register the postback or callback data for validation.
I do not want to disable the EventValidation. How can I register the data added at the client side to a particular element for postback validation at server side ?
I know the RegisterForEventValidation method is there, but I have never used it and even I don't understand from the msdn.
If anyone has ever done this, can you please share a sample code with brief explanation ?
To be honest I never had good luck with this, I found it much easier to subclass the necessary control just in that particular case in order to avoid ASP.NET attempting to validate it. This is better than turning of validation for the page as everything but that control will still be validated as always. I'm assuming in your case you're using a server side HtmlSelect (same can be done with DropDownList). Here is one option:
public class NoEventValdationHtmlSelect : HtmlSelect
{
}
You'll have to retrieve the selected value via Request.Form[UniqueNameOfControl] since SelectedIndex/Value/Item will be null on the server side.
In my case, I know all the values in advance that can be added to the ListBox at the Client side, so fortunately, there is a solution for this:-
protected override void Render(HtmlTextWriter writer)
{
Page.ClientScript.RegisterForEventValidation(lstBox.UniqueID, "ListItemValue
that can be added at client side");
base.Render(writer);
}

How to incorporate IsValid in a non-ASP.NET (standard html) approach button

I know that ASP.NET controls such as the button have the postback event model. And checking whether the page.IsValid is dependent on events and postback in order for the validation to kick in.
But what if I have a button using regular HTML inside my .aspx (and I don't want to use the asp.net button...please do not ask me why) yet still want to take advantage of calling Page.IsValid?
For example, lets say my .aspx page has 2 buttons:
<asp:ImageButton runat="server" ID="cmdPlaceOrder" OnClick="cmdPlaceOrder_Click" ImageUrl="images/someButton.gif" />
and that was there in the page, someone else had created that a while back. In the cmdPlaceOrder we check for Page.IsValid:
protected void cmdPlaceOrder_Click(object sender, EventArgs args)
{
if (!IsValid)
return;
... rest of logic
}
That's standard. Now what if I add a non-ASP.NET button like this in the .aspx page, used to place the order (but for a different kind of order seperate from the existing place order button above):
<img src="images/buttonPayGoogleCheckout.gif" alt="Pay with Google"/>
So on click of the hyperlink, the page posts back to itself (same url). I check the url for a querystring param flag that if set calls the method below that I created which is basically a similar method as the above but with a bit of different logic in it:
protected void PlaceGoogleCheckoutOrder()
{
if (!IsValid)
return;
... rest of logic here, but I can't get to it because there is no event model to allow IsValid to work
}
Obviously I'm not tying in an event model to this therefore once it hits the check for Page.IsValid it errors with the following message at runtime:
Page.IsValid cannot be called before validation has taken place. It should be queried in the event handler for a control that has CausesValidation=True and initiated the postback, or after a call to Page.Validate.
But I still want to be able to call this validation, the validation that's already been setup in our .aspx. I don't want to reinvent the wheel on this and I don't in this case want to use an ASP.NET based button (do not ask me why, I have my reasons and it's too long to get into that).
I want to know how I can still get that Page.IsValid check to work for a non-event driven button using . I'm not sure how to hook up an event to do so that still hooks in after the redirect and allows that code to still validate.
I tried adding Page.Validate(); inside my PlaceGoogleCheckoutOrder() method right before the check for Page.IsValid but I still get the same error.
After looking at MSDN on Page.Validate() (http://msdn.microsoft.com/en-us/library/0ke7bxeh.aspx) and it states "The validation group is determined by the control that posted the page to the server. If no validation group is specified, then no validation group is used."
So that's why nothing happened. So I'm not sure how to get ASP.NET in this case to know about the control (in this case my ) that posted the page to the server so that a validation group IS used. I guess I could add a runat="server" to my ...but doubt that's all I need to do here.
The trick with your normal button is that it never does a post back because your href attribute has some other url there. If you want to check if the page is valid, you have to post back to your page class first to make that check and then redirect from there.
What you can do to make this happen with a normal anchor (<a >) tag is process that anchor's onclick event in javascript, do any client side work you want, and then call the __doPostBack() javascript function.
You can see an example of how to call __doPostBack() on msdn here:
http://msdn.microsoft.com/en-us/library/aa720099(VS.71).aspx
It's from .Net 1.1, but still accurate.

Copy info from one dynamically created user control to another dynamically created user control

My ASP.NET WebForm has a place holder on it and user controls are dynamically added to it. The controls mostly have textboxes. Sometimes there are two user controls, sometimes there are ten. Everything is working as expected. My question is about how to implement a new feature.
My customer has a new request to copy data from the first control to another control checking a checkbox associated with the additional control in question.
At first, this sounded easy... Add a checkbox to the placeholder for each user control and then write some JavaScript to copy the data from the first control to the additional control. Then I realized that by those textboxes being in a user control, I don't really have access to modify the HTML inputs directly.
Next I started thinking about adding checkboxes that will automatically post back, but how do I go about dynamically adding a checkbox to a placeholder, and then come up with a way to add event handler to the checkbox and pass in the information necessary to loop through the controls and copy the values. This approach seems way too complicated with too much overhead to accomplish my goal.
Any suggestions?
You mentioned that since the checkboxes are in a user control, you don't have access to them.
Could you expose the ClientIDs using a property of the user control and then work with them in javascript? Something like this:
user_control {
int checkboxId { get { return checkbox.ClientId; } }
}
If you have more code that would be helpful...
This is probably too late to help you, but just so another answer is out there...
Including the checkbox as a part of the user control simplifies the issue considerably.
I had a similar situation, with maybe 10-15 UI controls in a user control, with a checkbox associated with the first one which, when checked, meant that I should copy the info from the first user control to all of the others.
Since it was all built in the codebehind, I simply exposed a boolean property of the user control named ShowCheckBox, which toggled the visibility of the checkbox. I set this to true in the first one, and false in all of the others. Thus, I knew that the event could only be raised by a click of the first user control's checkbox. Then, in the event handler for the checkbox, I handled the copying from the first user control to all of the others. (By the way, be sure to set AutoPostBack=true on that checkbox or you'll wonder why the event isn't firing.)
Javascript would definitely provide a better user experience, but this worked for me and didn't require me to figure out how to get the ClientId values into the javascript. (Although that's exactly what I need to do now, which is how I stumbled upon this question. :-) )

Child Control Initialization in Custom Composite in ASP.NET

Part of the series of controls I am working on obviously involves me lumping some of them together in to composites. I am rapidly starting to learn that this takes consideration (this is all new to me!) :)
I basically have a StyledWindow control, which is essentially a glorified Panel with ability to do other bits (like add borders etc).
Here is the code that instantiates the child controls within it. Up till this point it seems to have been working correctly with mundane static controls:
protected override void CreateChildControls()
{
_panel = new Panel();
if (_editable != null)
_editable.InstantiateIn(_panel);
_regions = new List<IAttributeAccessor>();
_regions.Add(_panel);
}
The problems came today when I tried nesting a more complex control within it. This control uses a reference to the page since it injects JavaScript in to make it a bit more snappy and responsive (the RegisterClientScriptBlock is the only reason I need the page ref).
Now, this was causing "object null" errors, but I localized this down to the render method, which was of course trying to call the method against the [null] Page object.
What's confusing me is that the control works fine as a standalone, but when placed in the StyledWindow it all goes horribly wrong!
So, it looks like I am missing something in either my StyledWindow or ChildControl. Any ideas?
Update
As Brad Wilson quite rightly pointed out, you do not see the controls being added to the Controls collection. This is what the _panel is for, this was there to handle that for me, basically then override Controls (I got this from a guide somewhere):
Panel _panel; // Sub-Control to store the "Content".
public override ControlCollection Controls
{
get
{
EnsureChildControls();
return _panel.Controls;
}
}
I hope that helps clarify things. Apologies.
Update Following Longhorn213's Answer
Right, I have been doing some playing with the control, placing one within the composite, and one outside. I then got the status of Page at event major event in the control Lifecycle and rendered it to the page.
The standalone is working fine and the page is inited as expected. However, the one nested in the Composite is different. It's OnLoad event is not being fired at all! So I am guessing Brad is probably right in that I am not setting up the control hierarchy correctly, can anyone offer some advice as to what I am missing? Is the Panel method not enough? (well, it obviously isn't is it?!) :D
Thanks for your help guys, appreciated :)
I don't see you adding your controls to the Controls collection anywhere, which would explain why they can't access the Page (since they've never been officially placed on the page).
I have always put the JavaScript calls on the OnLoad Function. Such as below.
protected override void OnLoad(EventArgs e)
{
// Do something to get the script
string script = GetScript();
this.Page.ClientScript.RegisterClientScriptBlock(this.Page.GetType(), "SomeJavaScriptName", script);
// Could also use this function to determine if the script has been register. i.e. more than 1 of the controls exists
this.Page.ClientScript.IsClientScriptBlockRegistered("SomeJavaScriptName");
base.OnLoad(e);
}
If you still want to do the render, then you can just write the script in the response. Which is what the RegisterScriptBlock does, it just puts the script inline on the page.
Solved!
Right, I was determined to get this cracked today! Here were my thoughts:
I thought the use of Panel was a bit of a hack, so I should remove it and find out how it is really done.
I didn't want to have to do something like MyCtl.Controls[0].Controls to access the controls added to the composite.
I wanted the damn thing to work!
So, I got searching and hit MSDN, this artcle was REALLY helpful (i.e. like almost copy 'n' paste, and explained well - something MSDN is traditionally bad at). Nice!
So, I ripped out the use of Panel and pretty much followed the artcle and took it as gospel, making notes as I went.
Here's what I have now:
I learned I was using the wrong term. I should have been calling it a Templated Control. While templated controls are technically composites, there is a distinct difference. Templated controls can define the interface for items that are added to them.
Templated controls are very powerful and actually pretty quick and easy to set up once you get your head round them!
I will play some more with the designer support to ensure I fully understand it all, then get a blog post up :)
A "Template" control is used to specify the interface for templated data.
For example, here is the ASPX markup for a templated control:
<cc1:TemplatedControl ID="MyCtl" runat="server">
<Template>
<!-- Templated Content Goes Here -->
</Template>
</cc1:TemplatedControl>
Heres the Code I Have Now
public class DummyWebControl : WebControl
{
// Acts as the surrogate for the templated controls.
// This is essentially the "interface" for the templated data.
}
In TemplateControl.cs...
ITemplate _template;
// Surrogate to hold the controls instantiated from
// within the template.
DummyWebControl _owner;
protected override void CreateChildControls()
{
// Note we are calling base.Controls here
// (you will see why in a min).
base.Controls.Clear();
_owner = new DummyWebControl();
// Load the Template Content
ITemplate template = _template;
if (template == null)
template = new StyledWindowDefaultTemplate();
template.InstantiateIn(_owner);
base.Controls.Add(_owner);
ChildControlsCreated = true;
}
Then, to provide easy access to the Controls of the [Surrogate] Object:
(this is why we needed to clear/add to the base.Controls)
public override ControlCollection Controls
{
get
{
EnsureChildControls();
return _owner.Controls;
}
}
And that is pretty much it, easy when you know how! :)
Next: Design Time Region Support!
Right, I got playing and I figured that there was something wrong with my control instantiation, since Longhorn was right, I should be able to create script references at OnLoad (and I couldn't), and Brad was right in that I need to ensure my Controls hierarchy was maintained by adding to the Controls collection of the composite.
So, I had two things here:
I had overriden the Controls property accessor for the composite to return this Panel's Controls collection since I dont want to have to go ctl.Controls[0].Controls[0] to get to the actual control I want. I have removed this, but I need to get this sorted.
I had not added the Panel to the Controls collection, I have now done this.
So, it now works, however, how do I get the Controls property for the composite to return the items in the Panel, rather than the Panel itself?

Dynamically added controls in Asp.Net

I'm trying to wrap my head around asp.net. I have a background as a long time php developer, but I'm now facing the task of learning asp.net and I'm having some trouble with it. It might very well be because I'm trying to force the framework into something it is not intended for - so I'd like to learn how to do it "the right way". :-)
My problem is how to add controls to a page programmatically at runtime. As far as I can figure out you need to create the controls at page_init as they otherwise disappears at the next PostBack. But many times I'm facing the problem that I don't know which controls to add in page_init as it is dependent on values from at previous PostBack.
A simple scenario could be a form with a dropdown control added in the designer. The dropdown is set to AutoPostBack. When the PostBack occur I need to render one or more controls denepending on the selected value from the dropdown control and preferably have those controls act as if they had been added by the design (as in "when posted back, behave "properly").
Am I going down the wrong path here?
I agree with the other points made here "If you can get out of creating controls dynamically, then do so..." (by #Jesper Blad Jenson aka) but here is a trick I worked out with dynamically created controls in the past.
The problem becomes chicken and the egg. You need your ViewState to create the control tree and you need your control tree created to get at your ViewState. Well, that's almost correct. There is a way to get at your ViewState values just before the rest of the tree is populated. That is by overriding LoadViewState(...) and SaveViewState(...).
In SaveViewState store the control you wish to create:
protected override object SaveViewState()
{
object[] myState = new object[2];
myState[0] = base.SaveViewState();
myState[1] = controlPickerDropDown.SelectedValue;
return myState
}
When the framework calls your "LoadViewState" override you'll get back the exact object you returned from "SaveViewState":
protected override void LoadViewState(object savedState)
{
object[] myState = (object[])savedState;
// Here is the trick, use the value you saved here to create your control tree.
CreateControlBasedOnDropDownValue(myState[1]);
// Call the base method to ensure everything works correctly.
base.LoadViewState(myState[0]);
}
I've used this successfully to create ASP.Net pages where a DataSet was serialised to the ViewState to store changes to an entire grid of data allowing the user to make multiple edits with PostBacks and finally commit all their changes in a single "Save" operation.
You must add your control inside OnInit event and viewstate will be preserved. Don't use if(ispostback), because controls must be added every time, event in postback!
(De)Serialization of viewstate happens after OnInit and before OnLoad, so your viewstate persistence provider will see dynamically added controls if they are added in OnInit.
But in scenario you're describing, probably multiview or simple hide/show (visible property) will be better solution.
It's because in OnInit event, when you must read dropdown and add new controls, viewstate isn't read (deserialized) yet and you don't know what did user choose! (you can do request.form(), but that feels kinda wrong)
After having wrestled with this problem for at while I have come up with these groundrules which seems to work, but YMMV.
Use declarative controls whenever possible
Use databinding where possible
Understand how ViewState works
The Visibilty property can go a long way
If you must use add controls in an event handler use Aydsman's tip and recreate the controls in an overridden LoadViewState.
TRULY Understanding ViewState is a must-read.
Understanding Dynamic Controls By Example shows some techniques on how to use databinding instead of dynamic controls.
TRULY Understanding Dynamic Controls also clarifies techniques which can be used to avoid dynamic controls.
Hope this helps others with same problems.
If you truly need to use dynamic controls, the following should work:
In OnInit, recreate the exact same control hierarchy that was on the page when the previous request was fulfilled. (If this isn't the initial request, of course)
After OnInit, the framework will load the viewstate from the previous request and all your controls should be in a stable state now.
In OnLoad, remove the controls that are not required and add the necessary ones. You will also have to somehow save the current control tree at this point, to be used in the first step during the following request. You could use a session variable that dictates how the dynamic control tree was created. I even stored the whole Controls collection in the session once (put aside your pitchforks, it was just for a demo).
Re-adding the "stale" controls that you will not need and will be removed at OnLoad anyway seems a bit quirky, but Asp.Net was not really designed with dynamic control creation in mind. If the exact same control hierarchy is not preserved during viewstate loading, all kinds of hard-to find bugs begin lurking in the page, because states of older controls are loaded into newly added ones.
Read up on Asp.Net page life cycle and especially on how the viewstate works and it will become clear.
Edit: This is a very good article about how viewstate behaves and what you should consider while dealing with dynamic controls: <Link>
Well. If you can get out of creating controls dynamicly, then do so - otherwise, what i whould do is to use Page_Load instead of Page_Init, but instead of placing stuff inside the If Not IsPostBack, then set i just directly in the method.
Ah, that's the problem with the leaky abstraction of ASP.NET web forms.
Maybe you'll be interested to look at ASP.NET MVC, which was used for the creation of this stackoverflow.com web site? That should be an easier fit for you, coming from a PHP (thus, pedal-to-the-metal when it comes to HTML and Javascript) background.
I think the answer here is in the MultiView control, so that for example the dropdown switches between different views in the multi-view.
You can probably even data-bind the current view property of the multiview to the value of the dropdown!
The only correct answer was given by Aydsman. LoadViewState is the only place to add dynamic controls where their viewstate values will be restored when recreated and you can access the viewstate in order to determine which controls to add.
I ran across this in the book "Pro ASP.NET 3.5 in C# 2008" under the section Dynamic Control Creation:
If you need to re-create a control multiple times, you should perform the control creation in the Page.Load event handler. This has the additional benefit of allowing you to use view state with your dynamic control. Even though view state is normally restored before the Page.Load event, if you create a control in the handler for the Page.Load event, ASP.NET will apply any view state information that it has after the Page.Load event handler ends. This process is automatic.
I have not tested this, but you might look into it.

Resources