Is there a better way to prepopulate fields? - asp.net

I am trying to create an edit form with the database values pre-populated in the front end. Right now I have lots of literal controls that act like placeholders and I assign the values for those on page load.
Is there a better way to do this? Or, is this the standard way of doing it?

Use databinding on the actual form fields. The syntax will vary depending on what your data source is, but in general it's something like this:
<asp:TextBox id="LastName" runat="server"
Text='<%# DataBinder.Eval(MyDataSource.LastName) %>'>
</asp:TextBox>

Related

asp.net (4) listview gives me troubles with generating id's

i'm in a asp.net listview, in the itemtemplate.
<asp:ListView runat="server" ClientIDMode="Predictable" ClientIDRowSuffix="Texttranslations_key"ID="lvwTextitems">
This is my code in the itemtemplate:
<span runat="server" onclick="openDiv('<%= EditItemDiv.ClientID%>')" style="width: 450px;"><%# Eval("Translation")%></span>
<asp:panel runat="server" id="EditItemDiv" style="display:none">
<asp:TextBox runat="server" ID = "EditItemArea" TextMode ="MultiLine" Rows="12" Columns="50" Text="<%# Eval("Translation")%>">
</asp:TextBox>
Now i have two problems.
First the span: i want the clientID of the asp:panel in the function openDiv(), so i can create some show hide functionality.
However, i get this as result:
<span onclick="openDiv('<%= EditItemDiv.ClientID%>')" style="width: 450px;">
my code isn't seen as code, but as plain text, and i don't know why?
Second, this line gets me a runtime error (The server tag is not well formed):
<asp:TextBox runat="server" ID = "EditItemArea" TextMode ="MultiLine" Rows="12" Columns="50" Text="<%# Eval("Translation")%>">
Can somebody help me out?
ps
at first i used this code for the generation of the id's: "myid<%# Eval("Id")%>" but that didn't workout either...
ps
i'm always getting in to trouble when using the Eval and the <%# %>, so it's probably some stupid thing (i hope)
For the first part, you definitely need to be using a binding expression:
<%# EditItemDiv.ClientID %>
The <%= %> scriptlet will have no context for each item. I assume you were "paraphrasing" the syntax you say you tried, so what didn't work before?
The "server tag is not well formed" is because you are trying to use double-quotes inside double-quotes. Change the outer to single-quotes:
Text='<%# Eval("Translation")%>'>
Basically, you can't nest similar quote types. Inline script will usually demand you use double-quotes, since single-quotes have a different meaning in c#, but you can use either double or single for markup parameter quoting. The upshot is that if you need to have inline script, use single quotes to wrap the markup parameter, which frees you to use double-quotes inside it.
If you need further single quotes in the output, e.g. to render a javascript parameter, just use '. You could also use " if you wanted to render double-quotes.
OnClientClick='openDiv('EditItem(<%# Eval("something") %>');'
As stated in my comment and by jamietre to fix the binding problem you need to change the code from:
Text="<%# Eval("Translation")%>"
to
Text='<%# Eval("Translation")%>'
As for the problem with the onclick of the span, it should work as you want if you just remove the runat="server" portion. I am not sure why, but it seems that adding this causes the controls to encode the onclick property.
If you need the runat="server" on the span then I will attempt to find another solution, but there are not guarantees.

TextBox: Display value in one format but return another format

i would like to display phone number fields on a website as (123) 456-7890 but have the system see it as 1234657890 when calling myTextBox.Text i am thinking this would require overriding the text property and cleaning it up in the overridden property but wanted to run this past the community.
Yes, the Text property is two ways. You would indeed have to format on output, and clean it up on input. However! Let me suggest that instead of using a TextBox for output that you use a Label or LiteralControl to display it. Then when the user edits, change to a textbox that doesn't have the formatting. The concept is from the DataBoundControls like:
<ItemTemplate>
<asp:Label Text=<%# FormattedText %> />
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox />
</EditItemTemplate>
If you are storing and retrieving the phone number as a ten-digit string, you can just format it when you display it, like this:
string.Format("{0,0:(###) ###-####}", phoneNumber);
Before you do that, you should test that the string actually contains 10 numeric characters.

ASP.NET: How to assign ID to a field in DetailsView?

I have a master-detail page, in which I use GridView to display multiple rows of data, and DetailsView + jQuery dialog to display the details of a single records. only one DetailsView is open at a time.
I need to be able to pull out a single field of the open DetailsView, for manipulation using JavaScript. Is there a way to give a unique ID to a given field in DetailsView, so I can use getElementByID? Or is there another way to accomplish what I'm trying to do?
Thank you in advance.
If you are using a bound textbox in a template field in your detailsview you can then select it by:
$("[id$='MyTextBox']");
Which will find the textbox bound to MyFieldName as below.
<asp:DetailsView ID="DetailsView1" runat="server">
<Fields>
<asp:TemplateField>
<ItemTemplate>
<asp:TextBox ID="MyTextBox" Text='<%# Bind("MyFieldName")%>' runat="server"></asp:TextBox>
</ItemTemplate>
</asp:TemplateField>
</Fields>
</asp:DetailsView>
Whatever guff asp.net adds onto the begining of the id won't matter because jQuery $= mean "ends with".
there may be a better way, but when I've needed an id available for js work, I just convert the bound field to a templated field. you can then give the textbox the id of your choice. keep in mind when rendered the id will be expanded with the id of the parent control.

Dynamic Id's not working in a GridView. Is there any way to prevent duplicate id's in a gridview?

My gridview has a template field with a label in it. I want to label the field using the QuestionID so that it doesn't create duplicate id's.
I tried doing the following:
<asp:TemplateField HeaderText="No">
<InsertItemTemplate>
<label id='<%# (string.Format("Label_{0}",
DataBinder.Eval(Container.DataItem,"QuestionID"))) %>'
runat="server"></asp:Label>
</InsertItemTemplate>
</asp:TemplateField>
But I got an error saying
The ID property of a control can only be set using the ID attribute in the tag and a simple value.
Does anyone know how to make it so that I can assign an id without it creating duplicate id's? I would like a way of accessing each one using javascript.
Thanks,
Matt
First of all, you're not getting this error because of the duplicate IDs. Whatever you give to your server control as ID, asp.net generates a new ID and renders it. Your exception is about evaluating the value into ID property I think.
IMO, let the asp.net generate the ID's for your labels. Add a class to your labels, and use JQuery to get all instances of your labels.
As an alternative, asp:Labels rendering spans as output, so you can change your code like that :
<asp:TemplateField HeaderText="No">
<InsertItemTemplate>
<span id='<%= (string.Format("Label_{0}",
DataBinder.Eval(Container.DataItem,"QuestionID"))) %>'>
</span>
</InsertItemTemplate>
</asp:TemplateField>

ASP.Net - Two way databinding of a single entity - Options, best way...roll your own?

I have been searching around to find the best option of doing this.
Basically, I want to do two way databinding of multiple controls (textbox, dropdownlist, checkbox, etc) to a single instance of custom class/entity, ie: Person.
It seems, the (only?) way to do this is using an like so:
<asp:FormView ID="FormView1" runat="server" DataKeyNames="OrderID"
DataSourceID="SqlDataSource1" DefaultMode="Edit">
<EditItemTemplate>
OrderID:
<asp:Label ID="OrderIDLabel1" runat="server" Text='<%# Eval("OrderID") %>' />
<br />
CustomerID:
<asp:DropDownList ID="CustomerIDDropDownList" runat="server"
DataValueField='CustomerID' DataSourceID="CustomerDataSource"
DataTextField="CompanyName"
SelectedValue='<%# Bind("CustomerID") %>'
/>
EmployeeID:
<asp:TextBox ID="EmployeeIDTextBox" runat="server"
Text='<%# Bind("EmployeeID") %>' />
<br />
Some issues:
- This is limited to using an ObjectDataSource control (ie: can't just use an instance of the desired class in the code behind)
- Forces you to define a second (likely identical layout) read only template....would be nice to have some some mechanism that could intelligently render a read-only view derived from the edit template.
- The binding declaration Text='<%# Bind("EmployeeID") %>' is loosely typed, so vulnerable to spelling errors
- etc
So my first question I guess is, is an asp:FormView the only way in ASP.Net to do declarative databinding of a single entity?
Secondly, how feasible would it be to hand roll some sort of a two way binding mechanism? I guess it would have to be reflection based, but I could live with that. Anyone recommendations on how one would declare the binding relationships in the aspx page? Would the proper way be like:
Text='<%# MySuperDuperBind("EmployeeID") %>'
And then somewhere (where?) my MySuperDuperBind implementation will get called as the page is rendered....how this is done is a bit beyond me though. And if I want to render in readonly, I can call a secondary function that will remove the editable UI control from the form and replace it with the corresponding read only version (ie: a Textbox is replaced with a Label).
Another alternative route is getting away from webforms and going to a client side templating solution such as this very nice looking solution:
http://weblogs.asp.net/dwahlin/archive/2009/05/03/using-jquery-with-client-side-data-binding-templates.aspx
However, I have no clue how to write the asp.net webservices properly in order to retrieve and save data in this type of an architecture.
Ideas?
is an asp:FormView the only way in
ASP.Net to do declarative databinding
of a single entity?
There's also DetailsView but it has the same issues.
I've mostly given up on 2-way databinding. It's great for prototyping and gets me 80-90% of the way to a complete solution but the last 10-20% is a nightmare. Binding any non-trivial object always seems to involve so many event handlers to customize behavior that it feels like spaghetti code to me.
I usually have two methods:
MapEntityToView(entity)
MapViewToEntity(entity)
that I call to display the entity and to populate from the page, respectively. It can be tedious to write but I don't have to wrestle with data binding issues.
I do use 1-way binding extensively for read only pages and displaying items in list controls.

Resources