I'm using Sitecore and just getting the hang of working within ASP.NET. We don't have a second Sitecore license for a development server, so I have to do everything live fire on the site (ack!), so I am trying to avoid working with code behinds due to the necessity of a recompile/DLL insert.
I'm just trying to hide a section header if the following section is empty. I've come up with this, which definitely works, but it seems pretty bulky:
<% if (!string.IsNullOrEmpty(Sitecore.Context.Item.Fields["Grades"].ToString())) { %><h2 class="edu">Timeframe</h2><% } %>
<sc:FieldRenderer runat="server" ID="mhTimeFrame" Fieldname="Timeframe" />
Is there a more straightforward way to do this?
By the way: I'm aware that Sitecore can utilize XSLT templates but our site was built without utilizing XSLT so I'd like to stick to one paradigm so that a future developer can make sense of this.
Just to state the obvious, you need to get a proper development process in place or you will get yourself into trouble! If you haven't already, talk to Sitecore and figure out what you need in terms of licenses to get a proper development environment up and running. You may be entitled to a development instance if you are a certified developer.
Now, to your question, you have to put the logic somewhere. If you are unable to modify the codebehind, compile and deploy then you need to put it on the .ascx. You can trim it up a bit I suppose...
<% if (Sitecore.Context.Item["Grades"] != "") { %><h2 class="edu">Timeframe</h2><% } %>
<sc:FieldRenderer runat="server" ID="mhTimeFrame" Fieldname="Timeframe" />
In order to get rid of the if-statement in your markup, you can set the visible attribute of your <h2 /> element:
<h2 class="edu" runat="server" Visible='<%# Sitecore.Context.Item.Fields["Grades"] != null %>'>
Timeframe
</h2>
To get this up and running, you need to trigger the DataBinding at least one time:
protected void Page_Load(object sender, EventArgs e)
{
Page.DataBind();
}
Nevertheless you NEED a development environment ;)
Related
From Web Form ASPX Markup
<tr>
<td><asp:Label ID="monstersPrimaryWeaponDamageTotalLabel" Text="Primary Weapon Damage: " runat="server" />
</td>
<td><asp:Button ID="PrimaryWeaponDamageButton"
Text="Update Primary Weapon Damage"
ValidationGroup="MakeMonster"
runat="server"
OnClick="MonstersPrimaryWeaponDamageTotalString"
</td>
<td><%=MonstersPrimaryWeaponDamageTotalString%></td>
</tr>
From Code Behind
string monstersPrimaryWeaponDamageTotalString = " -NA- ";
public string MonstersPrimaryWeaponDamageTotalString
{
get{return monstersPrimaryWeaponDamageTotalString;}
set{monstersPrimaryWeaponDamageTotalString = value;}
}
Error from web browser (FireFox)
Compilation Error
Description: An error occurred during the compilation of a resource
required to service this request.
Please review the following specific error details and modify your source code appropriately.
Compiler Error Message: CS0118:
'MakeMonsters.MonstersPrimaryWeaponDamageTotalString' is a 'property' but is used like a 'method'
Source Error:
Line 860: <td><asp:Label ID="monstersPrimaryWeaponDamageTotalLabel" Text="Primary Weapon Damage: " runat="server" />
Line 861:
Line 862: <td><asp:Button ID="PrimaryWeaponDamageButton
Line 863: Text="Update Primary Weapon Damage"
Line 864: ValidationGroup="MakeMonster"
In the error from the web browser it is highlighting line 862 as the problem. Although as you can see from the posted code from Visual Studio above that lines 862 - 864 are all part of the asp:button line.
What I am trying to do:
I have a webform that collects data for creating a character sheet in a roleplaying game. Then it writes that data to an XML file.
This is not a computer game, so don't think I can even begin to write that type of code. No, we play table top games the old fasion way, just I write the stories and am the GM (DM). All I am doing is putting my books in XML form so the players can access them from their laptops and phones. Saves lots of time and money from re-printing everything on paper. Not a computer program.
I am about halfway through and the XML file is created no problem.
Now, I want to modify the webform so that as I input certain data I can click a button next to certain fields that are calculated from various other fields and it displays the results for me in a separate blank field. The purpose of doing this is to see the results of what I have inputed so far before I finish the entire form and submit it to create the XML file.
Sorry I am not a professional. This is just hobby stuff, but have done a fair amount of reading on the Internet (just this forum and in Google), but probably do not know enough computer science theory to ask my question correctly to capture a useful answer.
Throw me some bones and I will try to edit my question and example code to be more useful to others seeking answers to this sort of thing.
The knowledge I am seeking is how to access the setter and getting from the webform. IE: what I want to do is click a button and have code behind do some calculations, string manipulation, and all that stuff, then store the result in a variable. Then, the webform will display the variable on the web page.
I am thinking my problem is understanding the whole, static, public, private, protected thing; but I have tried a dozen varieties of all that and just make a bigger mess.
As the error says I am trying to use a property as a method. Here is what I think I know about that.
A property is sort of like a variable (not sure the difference). Its designed to be a field in a database. In code behind, it behaves like a method (which in the old days before my hair got gray we called sub-routines, then functions). Properties, should be short and simple but can be accessed like methods - although I really don't see them as that similar.
A Method (is a function) and you can pass it quite a bit of data. Methods are for more complex needs, but they can be very simple.
You need to provide an event handler to the button:
protected void Btn_OnClick(Object sender, EventArgs e)
{
//yourCode
}
Your ASPX:
<asp:Button ID="PrimaryWeaponDamageButton"
Text="Update Primary Weapon Damage"
ValidationGroup="MakeMonster"
runat="server"
OnClick="Btn_OnClick" />
If this was not the issue, please clarify in your question
Page markup:
<asp:PlaceHolder ID="ph1" runat="server">
<%# _description %>
</asp:PlaceHolder>
<br />
<asp:Button ID="btnUpdateDescription" runat="server"
Text="Update Description" OnClick="btnUpdateDescription_Click" />
Code behind:
public partial class your_page : System.Web.UI.Page
{
public string _description;
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
_description = "descriptor";
ph1.DataBind();
}
}
protected void btnUpdateDescription_Click(object sender, EventArgs e)
{
_description = "new description";
ph1.DataBind();
}
}
The problem causing this error was not what I thought when I asked this question.
What I had been doing is converting all of my variables I declared outright:
For example like this
string railRoadTracks = "choo-choo";
into a more proper property set up with setters and getters
For example like this
private string railRoadTracks = "choo-choo";
public string RailRoadTracks
{
get{return railRoadTracks;}
set{railRoadTracks = value;}
}
When doing this Visual Studio offers to help by saving a bunch of re-typing and changing all the variables formally used as railRoadTracks to RailRoadTracks. It is merely and automated mass renaming function to make sure your program is using the new propety.
Visual Studio pops up asking if you want this done or not when you create the new property. In my ignorance I did not know what this popup meant and told it no. I went and manually changed the variables (called properties in new programmer speak) I was working with at the time, and left others unchanged.
Also changing other parts of the program to use public and private variables, I screwed everything up and my web page was trying to access once public variables that had become private.
The solution was to go and modify the entire program to use all the same properties.
this is my user control
<site:videoAxis ID="player" PlayerType="BlogPage" Width="620" Height="348" runat="server"/> I want to add a control DefaultVid dynamically.
what is the best way to add it?
Right now, I have it like this
<% if (ClipId > 0)
{ player.DefaultVid = ClipId;%>
<site:videoAxis ID="player" PlayerType="BlogPage" Width="620" Height="348" runat="server"/>
<%
} %>
It works correctly now. But I don't think that is the best way to do it. Any suggestions?
IMHO, the technique you posted is a good way to do this, and is likely what I would have done. There is nothing wrong with it, and, based on its simplicity, alternative preferences would likely just be matters of opinion.
with scrolling list box, the page will refresh(unwanted).
this problem is only in chrome (Version 27). In other browsers it works properly.
.aspx file:
<asp:Label runat="server" ID="label1" ></asp:Label>
<asp:ListBox ID="ListBox1" runat="server"
OnSelectedIndexChanged="ListBox1_SelectedIndexChanged"
DataValueField="f1" DataTextField="f2" DataSourceID="SqlDataSource1"
Rows="15" AutoPostBack="true" >
</asp:ListBox>
<asp:SqlDataSource ID="SqlDataSource1" runat="server"
SelectCommand="sp1" SelectCommandType="StoredProcedure"
ConnectionString="<%$ ConnectionStrings:ConnectionString1 %>">
</asp:SqlDataSource>
.cs file :
protected void ListBox1_SelectedIndexChanged(object sender, EventArgs e)
{
label1.Text = ListBox1.SelectedItem.Text;
}
We've noticed this unfortunate bug only recently, on a page that had been working without issue for a very long time. It is specific to Google Chrome version 27, and I am currently using version 26.
The bug:(clicking anywhere inside of the control - the scroll bar being the focus of the issue - causes a complete postback [provided you set the AutoPostBack attribute to true])
The bug could be at a higher level of scripting, and I'm not sure it affects all of our listboxes. It seems unlikely as we have many, on multiple pages, and we would be getting calls if all of them exhibited this behavior.
Our solution contained two options, with another option being less classy:
1) Impractical: to wait for an update for Google Chrome, or use version 26 explicitly. This is impractical for a large userbase which doesn't have permissions for installation or the ability to roll back to a previous version. It also doesn't work if you, for whatever reason, absolutely must test against the latest version of Chrome.
2) We have access to Telerik controls which enable us to use RadListBox instead, slightly more viewstate overhead which may not be a good solution for you, if it's an option at all. This was the option we chose, as the RadListBox escapes the problem behavior.
A distant third, substantially less appealing solution: Find some other alternative for displaying your data, such as a dropdown list, possibly with a secondary subselecting control if you're dealing with a particularly large set of information. It's more work, in the interim, and you would likely wish to revert your changes when a fix was made.
I know all of these are mediocre solutions, but they're possible workarounds. Sorry if this isn't much help.
This is a bug in some Chrome versions (as others have noted). I was getting the same behaviour on Chrome on an earlier v27 release.
You should upgrade Chrome to the latest version: my version is currently v 27.0.1453.116 m and the problem appears to be fixed in this release.
This is an issue in v27 of Chrome, updating to the latest version should fix this.
http://googlechromereleases.blogspot.co.uk/2013/06/stable-channel-update_18.html
The JavaScript function mypostback doesn't work if the listbox has SelectionMode="Multiple"
Disable the AutoPostBack for the ListBox, use the onClick attribute of the ListBox to run a javascript doing __doPostBack for it. It is a work around. I think Google should fix this Chrome bug (ver 27, and 28, ...). It, AutoPostBack True of ListBox, works fine at all other browsers. TY Pien.
<script type="text/javascript">
function mypostback(id, parameter)
{
__doPostBack(id, parameter)
}
</script>
<asp:ListBox ID="lstbox_id" runat="server" onclick="mypostback('lstbox_id','')">
</asp:ListBox>
It's definitely a bug in Chrome (e.g. v.27.0.1453.110 m). See this answer too.
I am coming from PHP so bear with me with my noobness...
I want to know a few things.
I know PHP, javascript and MySQL very very well now and I understand that browsers understand a few things.. html and javascript.
I ran through a tutorial of c#.net and found that it had pre-made "user controls" and i thought, oh my it's completely different from PHP... Then i realised that in the end it ends up with a bunch of javascript I could have written myself (not saying i want to ;), just saying).
My questions....
1.
If I have a table with some input fields:
<form id="form1" runat="server" method = "post" action = "validate_entry.aspx">
<table>
<tr>
<td>Name: </td><td><input type = "text" name = "name" /></td>
</tr>
<tr>
<td colspan = "2"><input type = "submit" value = "submit" /></td>
</tr>
</table>
</form>
and use the post and action methods, and then in validate_entry.aspx on Page_Load class I call something like:
c.Request["name"];
and do whatever with it.. Is this still a professional way of using c# or am i wanting it to be too much like PHP. Am i missing out on some execute speed or something even though it's running javascript.
2.
If I wanted to simply output the word "arse" in a div... If I do something like this, am I defeating the object of c#.net
<div id = "the_butt_holder">
<% Response.Write("arse"); %>
</div>
or a better example is that in my validate_entry.aspx page I do:
<div id = "the_response">
<% Response.Write(c.Request["name"]); %>
</div>
I think in your case, you would benefit greatly from looking at ASP MVC. It gets much closer to the grain and will probably be much closer to what you're used to working with as you have a great deal of control over the html.
Well James, I think you could start using asp.net mvc. It will be so easier to you than asp.net webforms. WebForms is based on Server Controls and Events, you cannot set a page in tag, instad of it you can create a , double click in it and write your code on .cs file respective of your webform, then, the .net framework will do a thing called PostBack and executes this event. There's a desnecessary long life cycle when a PostBack runs.
In Asp.Net webForms you don't have control of your output HTML code. The SErver Controls will do it for you, and sometimes it is not you want (or need).
With ASP.NET MVC you have a Route Tables and you have a MVC Architecture Pattern, so, if you use a mvc framework in PHP, it would be easy for you. With ASp.NET MVC you have control of your HTML, and you can create Typed Views. Check this link: http://www.asp.net/mvc
I hope it helps you.
Your way is by no means wrong, however there is another way in ASP.NET, which is to use actual TextBox (which renders input field) control instead of input field directly. That way, you will be able to access value as a property of the control.
<asp:TextBox id="tb1" runat="server" />
var text = tb1.Text;
Why not just write literal directly instead of outputting it like this?
<div id = "the_butt_holder">
arse
</div>
You may feel much more at home using ASP.NET MVC, and Razor layout engine. It's much more like PHP and Smarty (or whatever similar templating engine replaced it nowdays :) )
You can find more than enough tutorials right there on the site to get you started.
I've been working with a team on a ASP.NET project, a project management tool.
Most of the pages is basically writing stuff from the database to the page and store the changes which where made.
This is our first project in ASP.NET (We currently use ASP Classic for all our other projects), our senior told us not to use MVC.
The problem now is that our Designer/Front-end developer is pretty much clueless if it comes to ASP.NET, he also does not want to use VisualStudio if possible (He uses OSX).
For example:
What would for example be the best way to write a dynamic list?
This is what we currently do:
<div id="tasks" overflow-y="scroll" style="height:400px;">
<ul id='taskList'>
<% PrintTasks(); %>
</ul>
</div>
In the code-behind:
public void PrintTasks()
{
foreach (var task in _tasks)
{
Response.Write("<li rel='#' id='task_"+task.TaskID+"'>" +
...
"</span>" +
"</li>");
}
}
In this case, its not possible for the designer to edit the li tags without going into the code behind.
Thanks.
I'm afraid your front-end developer will have to suck it up and learn how to use VS. If your entire team is working on ASP.Net, there is no way to escape the wrath of VS.
MVC is a good for separation of C# and HTML. Razor engine allows a nice way to separate code and markup.
For you list you would probably do something like that in Razor:
#foreach (var item in items)
{
<li rel="#" id ="blah_#item.id">#item.text</li>
}
You should absolutely raise the question why MVC is not an option. It would be a much better fit for what you're doing, and the code quality would therefore also be much better, which helps the project overall. Not to speak of team productivity (and the ability for your designer to "escape" VS).
Doing some CSHTML with Razor you and your team would almost feel "at home".
According to your context, the main friction point is your front end developper.
So, decide on using a javascript framework (Knockout.js, angular.js, whatever).
Let your front-end developer design the UI that will get all needed info from JSON provided by your web stack of choice (ASP.NET MVC, Web Api, whatever).
This will ensure that he can develop his UI with the tool he wants. And you can work on the backend without worrying about UI. You just need to agree on the JSON contracts and stick to them.
This way, you will keep a clean separation of concerns with :
- everyone developping with the tools they're most at ease with
- no layer mix and match (ie having some HTML "generated" in your code behind)
And, your list will look like (using knockout) (syntax may not be accurate):
<ul data-bind="foreach: myList">
<li><span data-bind="text: Text, attr: { id: Id }" /></li>
</ul>
Code behind (using asp.net mvc) (syntax may not be accurate)
public JsonResult GetList()
{
var res = myServiceLayer
.GetListItems()
.Select(
x => new { Text = x.Val, Id = x.Id }
);
return JsonResult( res );
}
When using ASP.NET WebForms, I would give you the following suggestions:
Take advantage of CSS. Accept that your designer will not be able to edit the HTML produced by your code-behind, but if you use CSS intelligently you can probably overcome that challenge. In your example, you have a div and a ul element with id's, and the designer can then change the CSS to style these elements and child elements using the cascading properties of CSS. (Ex: #taskList > li)
Consider client side templating when appropriate. When presenting data for the user, fx. lists, consider using a templating framework. (jQuery fx) These templates can be placed in separate files that your designer can edit without VS. (Reference: load jQuery-Templates from external file?)
Spend some time learning the different controls available in ASP.NET WebForms, instead of using Response.Write to build HTML. Using Response.Write in the code-behind is generally a really bad practice and should be avoided, because your code will quickly turn into spaghetti and be unmaintainable. And if you're hoping to use ASP.NET WebForms (Or MVC) on later projects and want your senior and management to see the advantages of ASP.NET, then you and your team should spend a little time learning the framework. When you do that, you will be rewarded with more structured code that is easier to maintain. But if you use your current Classic ASP practices in ASP.NET, chances are that neither your senior or your management will see the benefits of using ASP.NET. And that would be a shame, because the benefits are really there. :-)
Good luck!
In the specific case you mentionned, in 'classical' asp.net, you're supposed to use a repeater: http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.repeater(v=vs.80).aspx
<asp:Repeater id="Repeater1" runat="server">
<ItemTemplate>
<li rel='#' id='task_<%# DataBinder.Eval(Container.DataItem, "TaskID") %>'>
<span>Whatever</span>
</li>
</ItemTemplate>
</asp:Repeater>
Basically, learn which webcontrols are available, create new ones every time it's necessary, and try to get as much as you can from asp.net webform's limited binding/templating system.
use Repeater here:
<asp:Repeater runat="server" ID="r1">
<ItemTemplate>
<li rel='#' id='<%# Eval("id","prefix{0}") %>'><span>
<asp:Label runat="server" ID="t1"><%# Eval("Caption") %></asp:Label>
</span></li>
</ItemTemplate>
</asp:Repeater>
and in cs file:
r1.DataSource=list;
r1.DataBind();