Multiple CMSEditableRegion in ascx? - asp.net

I have three CMSEditableRegion controls inside of an ascx which needs to be on an aspx page 3 or more times.
The problem is that each of the region controls will always contain the content of the last set of them.
After doing a little research, I've found out it saves the content of the control in the database under the ID of the control meaning that the first CMSEditableRegion will have its content overwritten by the last CMSEditableRegion's content (since there are at least three with the same server ID - one per ascx). Well, rather, that was for Kentico 5 but what I'm seeing tends to support this. Unfortunately, the solution I found for Kentico 5 does not work in Kentico 10.
How can I have multiple CMSEditableRegion controls in an ascx that is going to be on the aspx page multiple times?
Edit: We are indeed using the portal manager (correctly) and our master is set up using the specified Kentico Documentation.

You need to ensure each CMSEditableRegion's control ID is unique so that the data for each instance is stored separately in the database.
You can achieve this by setting the ID of the control in the codebehind file of your web part ascx.
Place the CMSEditableRegion into your ascx...
<cms:CMSEditableRegion runat="server" ID="cerContent" RegionTitle="WYSIWYG" RegionType="HtmlEditor" />
...and then set the control's ID in the code behind...
cerContent.ID = this.ID + cerContent.ID;
The unique ID is generated here by concatinating the control's ID with this.ID, which is the unique ID of the web part's instance when it is placed on a page.
Works for me in Kentico 10.

Add this to your web-parts code-behind.
public override void OnContentLoaded()
{
base.OnContentLoaded();
if (!this.StopProcessing)
{
theCMSEditableRegion.ID = theCMSEditableRegion.ID + base.ID;
}
}

When you use portal engine you can have as many as you want and that should apply to aspx development model. Did you follow the example?
I would look inside the DB to make sure that XML is saved correctly:
select CONVERT(xml,DocumentContent), * from cms_document where documentid = 123
When you save web parts (in portal engine this is the equivalent of CMSEditableRegion), the xml looks like this:
<content>
<webpart id="editabletext1;fe77e447-3af4-440f-a736-7c1e321cb3fc">456</webpart>
<webpart id="editabletext;3bb22493-8e7d-47c1-9dc0-dfc5aeff3157">123</webpart>
</content>
Yours should look the same or very similar. it might have something to do the IDs or bindings.

I think you are missing Portal Manager:
<cms:CMSPortalManager ID="manPortal" runat="server" EnableViewState="false" />
But easiest way to understand how this works is to open Kentico APX template in CMSTemplates/CorporateSite. In there you will find master page (root.master) with Home page template (HomeASPX.aspx). In master you can see portal manager is placed and in home you can add as many editable regions as you want. I did try this.
Hope this solves your problem.

Related

how create shared web from in asp.net

I am working on asp.net application for reporting. I need to develop round about 50+ reports. On each report I need selection criteria that may contain start-date , end-date, name , company etc on almost every .aspx page. these controls can be of type like dropdown, textbox or calender etc .
Any idea to use one editable + shared (not 100% same) web form on every page.
Using ASP.NET custom controls will allow you to create a module that you can insert into all of your pages.
You can also check this out to get you started more quickly.
http://www.codeproject.com/Articles/1739/User-controls-in-ASP-NET
If you want to make it similar but not 100% same for all apps then just create public properties that you can use to adjust control properties on different pages. For example if some text box should be visible on some page and not visible on other just create a public property in your control named something like EnableTextBoxABC
You can create ASP.NET Custom Controls.

Failed to load viewstate. The control tree into which viewstate is being loaded

I am receiving the following error message after an HTTP POST on an ASP.NET form hosted inside a UserControl:
Failed to load viewstate. The control tree into which viewstate is being loaded must match the control tree that was used to save viewstate during the previous request. For example, when adding controls dynamically, the controls added during a post-back must match the type and position of the controls added during the initial request.
Here's additional info:
I'm running .NET 4.5 RC
It's an Umbraco 4.7-based website
On my local dev machine the form works perfectly
This error only occurs on the staging server which has .NET 4.5 (only), MSSQL 2012 Express, IIS 7.5, Windows 7 (I know, it's not a real server yet, one day maybe...)
The server is not part of a web farm (or garden, tho that should be irrevelant)
The user control does render controls dynamically
I have applied all the latest service packs.
I have run out of ideas now! I have even restarted it and also performed a richual over the server involving a song and a special dance to no avail.
What is important when you are adding controls dynamically is on which event you are adding them.
If you added controls on events that occur after load, they will be part of the viewstate you send to the client.
You will have to add those controls again before LoadViewState is called.
If you run into cases where the decision of which controls to add is itself stored in the ViewState or the value of a control, then remember even before the ViewState is loaded, this data is available in Request.Params
Refer the asp.net page life cycle
I just added EnableViewState="false" to my page placeholder and its gone. Hope it works for u as well.
This Error Mainly Occurs during View state Change: From One Template To other Template like in case of Item Template, Edit Item Template, in Controls like Form View, List Views, Detail View, Grid View in ASP .net (all frameworks);
While Changing from control states say Item Template ---> Edit Template
the followings were going to alter
1) Controls will change (its ID & states)
2) Its Positions will change.
While Transformation of view if any post back occurs you will get Error as
Failed to load viewstate. The control tree into which viewstate is
being loaded....
if you are using separate control for data-binding like (button,link_button_Image_button events) you will get this error reported !
To avoid this error >>> Once state changes from one template to other within method you call data source binding ( Don't call during click or any post backing events ).
OK, so the answer is literally: "Set up a new server with all the same software as the last one and try again" and it works now.
I add "name" attribute with the same value as id, then this problem is gone.
<input type="button" id="extractBomInfoBtn" name="extractBomInfoBtn" value="Extract" class="button textonly" />
I had the same issue. This issue was at client end but it didn't occur in my local system.
After hours of googling, i had written EnableViewState="false" to my table tag in aspx page which has all the dynamic controls and then i removed all the viewstate variables and instead i created some hidden textboxes in the aspx page and accepted DB values into them in code behind and used them throughout my code. It then solved my problem.
But still, i couldn't figure out what was exactly the problem.
In my case I was manipulating the .Text property of a asp:Literal on page load which was causing the issue. In all other cases this never caused me a viewstate error but in this particular case I was changing the .Text value to an html element.
The following caused the error:
<asp:Literal ID="SvgIcon" runat="server" />
SvgIcon.Text = "<svg version=\"1.1\" id=\"Layer_1\" bla bla />"
I was able to resolve the error by adding EnableViewState="false" explicitly to the control:
<asp:Literal ID="SvgIcon" runat="server" EnableViewState="false" />
Check if you have the binding method of the control directly in your page load event. This can cause this problem.
You can add new PlaceHolder per UserControls
OR
You can set enableviewstate=false on the control , if you dont need viewstate
In my case I had a grid view with (OnPageIndexChanging) event
and when I click on a page nothing will happen until I click it twice!
I was refreshing the data source before setting new page index.
This is what I was doing wrong
grd.DataSource = data;
grd.DataBind();
grd.PageIndex = e.NewPageIndex;
This is the right way
grd.PageIndex = e.NewPageIndex;
grd.DataSource = data;
grd.DataBind();
This can happen if you override SaveViewState in your control but don't override LoadViewState.
So I actually ended up discovering that the list of entities I was binding to was not in the same order as the controls in ViewState! I'm still working thru a cleaner solution, but my code is working with ViewStateEnabled = true by having the method which reconstructs my dynamic controls (called from Page_Load) do it differently if !IsPostBack.
Ultimately, I will probably need to fix my sorting algorithm for my nested dynamic controls, but suffice it to say: if you are using the same pattern as I am, of using a List to generate/bind to dynamic controls, and that order is fluid or changing, try comparing Request.Params to find the keys that are relevant to your control hierarchy, and see if they match the order of your List. That solved my issue. Kudos to #nunespascal!
In short, I am dynamically generating all but one tab in an AjaxToolkit tab control, and then populating that with a couple layers deep of placeholders and regular controls (textboxes, dropdownlists, etc), so that's why it's complicated to get the order of everything correct.
Although this is very old question, I had visited this as I got the similar issue. But my issue was generated just because I have added a javascript code in Master page in head tag. That javascript code is reading a value of Session["KeyName"] ,
Code is like below -
$(document).ready(function () {
var allowOpenInNewTab = false;
allowOpenInNewTab = '<%# Convert.ToString(Session["AllowOpenInNewTab"]).ToLower() %>' == 'true';
if (!allowOpenInNewTab && window.sessionStorage.tabId != '1') {
alert("This page is not allowed to be open in another tab, sorry we can not load the page!!");
}
});
When I remove above code then everything was running smoothly but if I keep adding this part of code, it was giving this error of
Failed to load viewstate. The control tree into which viewstate is being loaded must match the control tree that was used to save viewstate...
Finally I found the solution like if I move my javascript code from head to just before the end of the body tag.
So solution that worked for me was moving javascript code (which is reading Session value from Server tags) to just before end of body tag.

Can we use multiple forms in a web page?

So far, all the web pages I met contain at most one <form> tag. Why not multiple ones? I can not think of reasons why multiple forms can't coexist within the same web page.
Also, to be specific to ASP.NET - why are all the server controls are placed within the <form> tag? Why not place them somewhere else?
Plus,
I noticed that in an .aspx file, the <form> tag has the runat=server attribute, while a normal server control such as Button also has one. So it seems the <form> is also a server control. But strangely enough, I cannot find it in the Visual Studio Toolbox.
There can be multiple forms, with hacks.
It is indeed a shortcoming of WebForms. In ASP.NET MVC you can implement as many forms as you want (and it is valid & correct behavior of web pages).
The reason all server controls are placed inside <form> tag is to allow the WebForms engine to recognize them, load their values & save their values from/to the ViewState. Almost all infrastructure of control management in WebForms is based on the idea that a tag contains everything you access from the code-behind.
As pointed out, this is one of the shortcomings of WebForms. I do want to point out, additionally, that with cross-page posting and validation groups, you can typically reach your desired behavior (for most "multi-form" solutions).
Regarding the additional question: the <form runat="server"> is parsed as HtmlForm class behind the scenes, which inherits from HtmlControl like any other HTML element with runat="server".
Unlike any other HtmlControl though, there can exist only one instance per page and it does not appear in the toolbox as it's added automatically to every new Form you create, so it's quite pointless.
Yes, it can be done - by creating a custom HtmlForm object and toggling the forms as needed. I've just answered a similar question here (with code):
Paypal Form Ruins My ASP.NET webforms layout -> How to Solve?
many non server forms - you can , but only one runAt Server form
i also found this :
A server-side form tag is the tag which has a runat="server" attribute. If this attribute
is missing, then it's a typical HTML form tag. The conclusion is that you are allowed to use
multiple form tags on a page, as long as only one has the runat="server" attribute. The
disadvantage of the form that doesn't have this attribute, is that view state won't work
(meaning form values will disappear when using the back/forward browser buttons). It's a
small price to pay if you really need multiple forms on a page.
Take master page & set design.
Take one form in master page.
Second form take in contain place holder.
In contain place holder in only for write form tag (not use)
Add aspx page & design second form but not write form tag only for control put
Take button click event fire code write
This is proper way of two form

Reuse a Variable Multiple Times on an ASP.NET Page

I feel somewhat foolish asking such a simple question, but I can't seem to find an answer. I'm new to ASP.NET (C#), but I'm learning by building a simple set of web pages that display a report. I have a variable that represents a company name. I need to output this variable in multiple places on the web page. The only way I have found to output a variable this is with:
company_name.Text = "Acme Windows";
then
<asp:literal id="company_name" runat="server" />
My problem is that I want to use company_name in multiple places on the page. Do I really have to create a separate variable holding the the same value for each time it is placed on the page? If I just copy the above XML code to all the places I want to show the variable it obviously creates a compile error since that ID is already defined.
I feel like I'm missing something very obvious.
The easiest way to do this is to create a string variable or property in your code-behind class and use the <%= %> notation (short for Response.Write) to render it on your page inline:
// You can do this anywhere on your .aspx, as many times as you like.
<%= this.CompanyName %>
// Better yet, html encode the value to protect against various threats,
// such as cross-site script injection (XSS)
<%= HttpUtility.HtmlEncode(this.CompanyName) %>
.NET 4.0 introduces a new shortcut notation (Html Encoding Blocks) to html-encode your output:
<%: this.CompanyName %>
Regarding your original approach, ASP.NET web controls like Literal represent individual parts of a web page - you can't use them multiple times on a page because the object instance company_name refers to the specific part of the HTML generated by the <asp:literal> in your .aspx page.
In this case, you create a property on the page and output that in every place you need it.
public string CompanyName { get { return "Acme Windows"; } }
And in the aspx:
.NET 4.0:
<%:this.CompanyName%>
Before 4.0:
<%=this.companyName%>
You could add the control dynamically:
Literal myLiteral = new Literal();
myLiteral.text = "Acme Windows";
this.Page.Controls.Add(myLiteral);
You can also add the control within a specific control on the page, by changing the this.Page.Controls reference to the particular control you want to add the literal to.
Why is this a community wiki?
Anyway, you have several possibilities to achieve what you want. Placing multiple variables holding the same name is for sure not best practice. If you have it filled with, let's call it, "semi-dynamic" value, I'd not put it hardcoded within your code. What I would do is to use a global resource file.
You create a new resource file in the App_GlobalResources folder and add a key "COMPANY_NAME" with value "Acme Windows". Then within your ASPX code you can do something like
<asp:literal id="company_name" runat="server" Text="<%$ Resources:GlobalResources, Button_Save %>"/>
I've written a blog post some time ago which details this approach. The advantage of the resource file is that you don't have to touch the code.
If you want to further "refactor" then - assuming you have some general company info you have to display on different positions on the page - you could create a separate UserControl which contains the information like company name, phone number, contact info etc. Within that control you have your literal, label, whatever you use to display that information exactly 1 time. This UserControl is then placed on the places on the actual page where you need it, even multiple times.
The simplest answer is you need to define multiple controls.
But a better solution would be to do this:
Create a property on the code behind side of things:
protected CompanyName{get;set;}
Then, in the aspx side of things, reference that with the <%= %> commands
<span><%=CompanyName %></span>

Strange Problem with asp.net website

I've built an asp website and i have the following issues:-
i'm using a master page in it and have defined two contentplaceholders one in head one in content, and i've specified the page title in the top most directive at the #page directive but the page title doesn't show up. I have to manually add a tag for it.
Secondly when i create a content page from a master page it creates it and when i rename it, it doesn't rename it's class. It remains _Default, thus every page was having an inherit to _default.
Most importantly
I'm using a page to enter and view data to the database. I've used a boolean called isadmin which i set according to credentials at page load. and i'm added a panel where it's visible property is set to Visible = '<%#IsAdmin %>'. It works properly when i run it through the visual studio environment but when i publish it and run it doesn't work and the panel just comes and stays there. Why is it happening? Any idea?
Thanks
The Visible problem is fixed as i had to enable windows authentication on the server. Awaiting answers for the other two issues. Thanks
Try to add a <head runat=server> to the master page. Only then ASP.net can "see" the tag and modify it
It is not that bad that several aspx-pages have identical class names. ASP.NET 2.0 started to process every page as its own compiling unit or so. Pages cannot see each other. There is a special directive to make pages see each other and instanciate or manipulate them. So it should not do much harm
Maybe you did not test this correctly and are mistaken that it DOES work in Visual Studio??? But in any case I would suggest that you move your logic into OnInit, then it runs much earlier. I think the control tree is build before Page.OnLoad. What you do is data binding, that might run only if DataBind is called, I'm not sure
Or use the safe way: Make IsAdmin a property so that it initializes itself on first call and caches the result in a variable
Regarding question #2 - add your content pages via Project -> Add New Item, and name it appropriately there. That way the naming is consistent and correct throughout.
Regarding #3, what HTML is output when you run it from the server?
your first issue can be solved by filling out the title part of the #Page directive in your .aspx pages. The master page will display that text in the browsers title bar.
and prob #2 should be solved by adding the files using the file add option in visual studio.

Resources