SiteFinity 4.0: Trouble Accessing Postback Data in Custom User Control - forms

I'm trying to get a highly customized hand built form into sitefinity 4.0 and my problem is that no matter what I do I can't access the form's postback data in the code behind. My form is a user control and I've added it in the way described here:
http://www.sitefinity.com/40/help/developer-manual/controls-adding-a-new-control.html
After struggling for several hours, I created a basic test form and I'm still not able to access the postback data. I've also tried adding EnableViewState="true" all over the place but the form data is still empty on postback. The exact same user control runs and posts data perfectly outside of sitefinity. I also tried other methods of accessing the postback data and I discovered that Request.Form does contain the data I need. I'd still love to access my form elements in the usual way though, so I don't have to do Request.Form for every control on the page and loop that way, which seems really hokey.
Here's the code for the basic form:
"BasicUserControl.ascx"
<%# Control Language="C#" AutoEventWireup="true" CodeBehind="BasicUserControl.ascx.cs" Inherits="SitefinityWebApp.UserControls.Assessments.BasicUserControl" EnableViewState="true" %>
<div id="assessmentDiv" runat="server">
<asp:TextBox ID="TextBox1" runat="server" clientidmode="Static" enableviewstate="true"></asp:TextBox>
<asp:Literal ID="Literal1" runat="server" clientidmode="Static" enableviewstate="true"></asp:Literal>
<asp:Button ID="Button1" runat="server" Text="Button" />
</div>
"BasicUserControl.ascx.cs" Code Behind
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace SitefinityWebApp.UserControls.Assessments
{
public partial class BasicUserControl : System.Web.UI.UserControl
{
protected void Page_Load(object sender, EventArgs e)
{
if (IsPostBack)
{
Literal1.Text = TextBox1.Text;
}
}
}
}
Again, if I add the control via the method described at the link above, I am able to successfully create a Sitefinity 4.0 CMS page, drag the control onto it, run the page, step into the code behind using the debugger, yet when VS2010 reaches the line below there is no form data being posted:
Literal1.Text = TextBox1.Text;
FYI: The reason why there is no form tag in my usercontrol.ascx code above is because I get an error when running the form thru sitefinity that only one server-side form tag can exist on a .net page (sitefinity injects it's own form tag).
Thanks in advance for your help!
Ben

Never mind - I figured it out. For some reason, data isn't available at the Page_Load stage of the .net page lifecycle in a sitefinity form submission (at least not via a custom user control). If I wait until the Page_PreRender stage to retrieve the data from the form on the page, it's all there.
My current prevailing theory is that Sitefinity 4.0 grabs the postback data when a form submits and hasn't finished monkeying around with it at the Page_Load stage, so you have to wait until the Page_PreRender stage before sitefinity has injected the data back into the page cycle.

I had the same issue you did and came to the same solution. Spent a bunch of time on it - wish this answer had been around then.

Try adding enableviewstate into masterpages. I had the same situation and solved with this.
Also checked "enable view state" when creating pages.
Hope this help.
`<%# Master Language="C#" AutoEventWireup="true" CodeFile="HomePageClubManavgat.master.cs" Inherits="App_Master_HomePageClubManavgat" EnableViewState="true" %>
<script type="text/C#" runat="server">
protected override void OnInit(EventArgs e)
{
this.Page.EnableViewState = true;
base.OnInit(e);
}
`

Related

Unable to redirect from sharepoint event receiver

I have created an event receiver on the "Task" list.
If the "Due Date" is null then the user should be redirected to the custom error page.
Custom error page resides in the SharePoint mapped folder under "Layouts" directory.
The event receiver code is as follows:
public override void ItemAdding(SPItemEventProperties properties)
{
try
{
if (properties.AfterProperties["Due Date"] == null)
{
properties.Status = SPEventReceiverStatus.CancelWithRedirectUrl;
properties.RedirectUrl = "_layouts/CustomErrorPage/DueDateErrorPage.aspx";
}
}
catch (Exception ex)
{
}
}
The custom error page which is of type "Application Page" having name. "DueDateErrorPage.aspx". The mark up is:
<asp:Content ID="PageHead" ContentPlaceHolderID="PlaceHolderAdditionalPageHead" runat="server">
</asp:Content>
<asp:Content ID="Main" ContentPlaceHolderID="PlaceHolderMain" runat="server">
ERROR : You cannot create the task without due date
</asp:Content>
<asp:Content ID="PageTitle" ContentPlaceHolderID="PlaceHolderPageTitle" runat="server">
Custom Error Page
</asp:Content>
<asp:Content ID="PageTitleInTitleArea" ContentPlaceHolderID="PlaceHolderPageTitleInTitleArea" runat="server" >
Custom Error Page
</asp:Content>
Though in IIS, under the _layouts direcory the page is available I am getting this output.
How should I tackle this error? Please help.
I think your redirect url is invalid, because it will be relative to the current page, and not the current site or site collection.
You can diagnose this by looking at the dialog frame properties, and check the url.
Method 1 : solve the amgiguity
To resolve ambiguity, I suggest you to use the SPUtility.GetServerRelativeUrlFromPrefixedUrl method.
This will create a correct url.
Especially, change your code like this:
properties.RedirectUrl = SPUtility.GetServerRelativeUrlFromPrefixedUrl(
"~site/_layouts/CustomErrorPage/DueDateErrorPage.aspx"
);
This will dynamically resolve ~site to your current SPWeb url. You can also use ~sitecollection to resolve the site collection.
Method 2: make the field mandatory
Why don't you simply make the due date mandatory?
Method 3: use the standard sharepoint error page (not tested I admit)
Instead of redirecting to your own page, "Cancel" the event with a custom error message:
properties.Status = SPEventReceiverStatus.CancelWithError;
properties.ErrorMessage= "Due date is mandatory";
Moreover, CancelWithRedirectUrl is now obsolete.
PS: as a side note, you should know that a SharePoint dedicated Stack Exchange site exists.
First of all I first checked the url in web browser that is:
/_layouts/CustomErrorPage/DueDateErrorPage.aspx
It was opening the page that means the page is available but there is something missing in the url only.
So by using the SPUrlUtility class I was able to redirect the page.
The changes I needed to made was:
properties.RedirectUrl = SPUrlUtility.CombineUrl(properties.WebUrl,"/_layouts/CustomErrorPage/DueDateErrorPage.aspx");
It's working perfectly..

redirect to custom php file after custom contact form is submitted in Magento

I made a CMS page to include a form I created but want the form action to send to /template/contacts/report.phtml
Currently I have this in my form but I know its not right.
<form action="report.phtml" id="contactForm" method="post">
Thanks for helping!
Magento has built in magento standard contact form. You can access it from browser www.yourdomain.com/contacts
That's managed by the controller in app/code/core/Mage/Contacts/controllers/indexController.php and the function called
public function indexAction()
and the action on the form is in http://www.yourdomain.com/contacts/index/post/ which is managed by the same controller and a function called
public function postAction()
If your aim to have completely custom form (by adding extra fields), the Magento way, you need to create an extension and have your own controllers that you can access it from browser.
or
the hacking way, you can create new function called customAction() with the same code with postAction(). you can copy app/code/core/Mage/Contacts/controllers/indexController.php and create new file in app/code/local/Mage/Contacts/controllers/indexController.php
and copy the whole
public function postAction(){
until the close of the function.
}
And paste it and rename the function customAction(). And if you want customise redirection. you can change the code inside your customAction()
Mage::getSingleton('customer/session')->addSuccess(Mage::helper('contacts')->__('Your inquiry was submitted and will be responded to as soon as possible. Thank you for contacting us.'));
$this->_redirect('*/*/');
to
Mage::getSingleton('customer/session')->addSuccess(Mage::helper('contacts')->__('Your inquiry was submitted and will be responded to as soon as possible. Thank you for contacting us.'));
$this->_redirect('http://yourdomain/redirect_url');
And the action on your form you can pointed to http://www.yourdomain.com/contacts/index/custom/
Hope that's help.

Java Web Architecture

I am interested in putting together a URL Auction research site. It will be structured as a standard [Presentation Layer <-->Business Layer <--->Data Layer]. This site will have an index.html that will allow users to enter a url they are interested in. That index.html will then call a doPost method via servlet which in turn spits out a results page of whether or not that URL is for sale like so:
index.html
<html>
<head>
<title>URL Auction Search Page</title>
</head>
<body>
<CENTER>
<FORM ACTION="/ResultServlet/Results" METHOD=GET>
<INPUT TYPE=TEXT NAME="st">
<INPUT TYPE=SUBMIT VALUE=Submit>
</FORM>
</CENTER>
</body>
</html>
Servlet:
#WebServlet("/Results")
public class Results extends HttpServlet {
private static final long serialVersionUID = 1L;
public static String str="";
private String businessLogic(String q){
try {
str = new compute.URL.GetAvailURI( "https://www.registerdomains.com/auctionAPI/Key:a05u3***1F2r6Z&urlSearch="+q);
/*more boring number crunching */
return str;
}
/*
protected void doGet(HttpServletRequest request, HttpServletResponse response)
}
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
Results r = new Results();
String st = request.getParameter("st");
response.sendRedirect("results/resultActionURL.html?st="+r.businessLogic(st)");
}
}
However, there will be 2 other links from the results page that I need to process. Namely, a link called WhoOwnsThis.html which takes whois data and geographically maps this information on Google maps. Also, AppraiseResult.html that gives a real time appraisal of the url in question. OK- these 2 pages will take time (very loosely we’ll say 2 sec. ea.) to crunch so I am presenting the user with the results page while I then go on in the background and create the data for each of the other two results pages.
Question-
How do I handle the statefulness of these three results pages? My first thought is to create a unique directory each time the two additional results pages are created(WhoOwnsThis and AppraiseResult). Then I can embed the unique dir name as an argument in the results page url so that when they click on the link to the other 2 results pages, the dir name will be pulled from the results page url as a .js var and inserted to get the right page. However, I am also reading up on REST and wondering if that is a better way of handling the state for this transaction. What would industry standard recommend in this scenario?
Do you really want to work with such a low level API as Servlets? If you are open-minded look at Play Framework 2.0 and get the same experience as everyone on other platforms enjoy. If not, Spring MVC is a good choice. And if you prefer to just have JavaScript frontend then JAX-RS is a good choice.
Note that Play Framework 2.0 includes it's own class reloading mechanism, but you get the same experience with JRebel in other frameworks as well.
State in general is good to keep in the database, so it will be easy to scale. Java EE 6 Web Profile also gives you stateful session beans. Spring MVC has session scoped beans. Each of them do it in their own way, but as it is such a basic concept, there is plenty of documentation on their site and I'm not going to paste it here.
Have fun and welcome to the era of simple Java :)
I think the more modern layering is four-tiered:
View->Controller->Service->Persistence.
You can choose between asking the Java EE app server to maintain state for you either in the web tier via sessions or as stateful services in the service layer.

How to Update asp:Label after AJAX Callback

I'm using the ajaxtoolkit:Rating. It all works fine except I'm trying to write a value to an asp label on the changed event and can't get it to work. Here are the relevant lines of code:
page.aspx
<asp:LoginView ID="LoginView1" runat="server">
<LoggedInTemplate>
<td>
<ajaxtoolkit:Rating ID="YourRating" runat="server" BehaviorID="RatingBehavior1" CurrentRating="0"
MaxRating="10" StarCssClass="ratingStar" WaitingStarCssClass="savedRatingStar"
ReadOnly="false" FilledStarCssClass="filledRatingStar" EmptyStarCssClass="emptyRatingStar"
OnChanged="YourRating_Changed" />
</td>
<td>
(<asp:Label ID="YourRatingNumber" Text="" runat="server"></asp:Label>)
</td>
</LoggedInTemplate>
<AnonymousTemplate>
<td>
Login or Register to Rate
</td>
</AnonymousTemplate>
page.aspx.cs
protected void YourRating_Changed(object sender, AjaxControlToolkit.RatingEventArgs e)
{
((HtmlGenericControl)FindControl("MainContent_LoginView1_YourRatingNumber")).InnerHtml = e.Value;
}
What I'm trying to do is update my asp:label control named "YourRatingNumber" text to e.value. I've tried many ways. I realize the asp:label is rendered as a span tag but I can't seem to access that value either. How can do this?
Thanks ... Bob
AJAX is asynchronous, meaning that a page load does not occur. Changing the value of a label server-side during an AJAX operation causes nothing client side. You would need to signal the client to update the page. You should use javascript to do this. I do not think you can do this using Web Forms. If you use MVC, you can use their AJAX helpers to do this, but it would require rewriting the site.
I would suggest that you write some javascript to cause an AJAX event and have it update the label when it gets a response. I would also suggest reading http://w3schools.com/ajax/default.asp, it explains how to use javascript to create AJAX requests, but you would need to tweak it a little to work with asp.net.
Also note, you should include whether you are using Web Forms or MVC, although they are similar, they have different handling of AJAX.

Handling 'A potentially dangerous Request.Form value was detected from the client'

I am trying to figure out how to handle this error.
A potentially dangerous Request.Form value was detected from the client
The error occurs when a user enters in html or xml tags( <p> or <HeyImXML>) and tries to submit a form. The input is not supposed to contain any sort of markup at all, just plain text.
I am using model binding validation in ASP.NET MVC 2.0 along with Html.EnableClientValidation. This works fine as long as there is no markup entered.
What is the best approach on how to avoid this error message?
My guess is to write a new validation class which checks for this kind of markup?
I want to catch the error in this specific instance. To clarify there is an area with a form for siteadmins that can enter markup and there is a normal users area where they can not enter markup. However this error page appears when a normal users enters markup. My question is, how do I handle this to prevent the site from crashing and showing the error page. I want to display a cleaner error.
MVC will automatically protect your application from some html injection and cross-site scripting (XSS) attacks. This is why you will get the "A potentially dangerous Request.Form value was detected from the client (...)" by default when attempting to post html/javascript.
However, we may sometimes want to allow our users to post html. You might just want to allow users to use characters such as "›", or it might be because your implementing blog functionality and want to support tags like ‹h1›, ‹div›, etc. This can easily be accomplished with MVC by disabling request validation.
Add [ValidateInput(false)] attribute to the action method in the controller you are calling. This will disable request validation for the entire model on the specific action.
Another way is to add the [AllowHtml] attribute to the property which requires html in your model.
These two attributes will only allow html/javascript to GET IN to your application, but MVC will still output them safely by using html encoding. If you want to output it like html, you can use the #Html.Raw(#Model.Content). But use this with caution, since this will open your application to cross-site scripting attacks (XSS)!
i found this solution from some one's blog
also see below code for your solution
you can handle errors within your application in the following way
1. Setting the CustomErros mode section in your Web.Config file of your application
This the lists of options the mode attribute can accept.
RemoteOnly: Generic error pages are shown for remote users. Rich error pages are shown for local requests (requests that are made from the current computer). This is the default setting.
Off: Rich error pages are shown for all users, regardless of the source of the request. This setting is helpful in many development scenarios but should not be used in a deployed application.
On: Generic error pages are shown for all users, regardless of the source of the request. This is the most secure option.
<System.Web>
//map all the erros presented in the application to the error.aspx webpage
<customErrors mode="RemoteOnly" defaultRedirect ="~/error.aspx" />
<System.Web>
2. throught Global.asax file in the Application_Error function
//handle all the errors presented in the application
void Application_Error(object sender, EventArgs e){
Server.Tranfer("error.aspx");
}
I hope this works for you.
from stackoverflow solution
This was introduced early on in ASP.Net to try to help prevent script injection attacks. It isn't unique to MVC.
If you don't want this feature, you can turn it off and write your own.
To disable request validation on a page, set the validateRequest attribute of the Page directive to false:
<%# Page validateRequest="false" %>
To disable request validation for your application, modify Web.config - set the validateRequest attribute of the <pages /> section to false:
<configuration>
<system.web>
<pages validateRequest="false" />
</system.web>
</configuration>