I have a ASP.NET 4.5 web forms site using EF 5.
One of the object of my data model is a 'medical file' with a DateTime property (among the others):
public partial class MedFile {
public System.Guid MedFileId { get; set; }
public string Name { get; set; }
public Nullable<System.DateTime> MedDate { get; set; }
...
}
Here it is the snippet of the web form for editing:
<asp:ListView ID="MedFilesForm" runat="server"
ItemType="MedFile" DataKeyNames="MedFileId"
SelectMethod="GetFiles"
UpdateMethod="UpdateFile">
...
<EditItemTemplate>
<asp:Label ID="Label1" runat="server" AssociatedControlID="TextBox1">Name</asp:Label>
<asp:TextBox ID="TextBox1" runat="server" Text='<%# Bind("Name") %>' />
<asp:Label ID="Label2" runat="server" AssociatedControlID="TextBox2">Data</asp:Label>
<asp:TextBox ID="TextBox2" runat="server" Text='<%# Bind("MedDate", "{0:d}") %>' />
<asp:LinkButton ID="UpdateButton" runat="server"
CausesValidation="true" CommandName="Update"
</asp:LinkButton>
</EditItemTemplate>
</asp:ListView>
Note the UpdateMethod="UpdateFile" and the TextBox2 with the Bind("MedDate", "{0:d}").
Finally here it is the UpdatedFile in the code behind:
public void UpdateFile(Guid medFileId) {
// get the current med file from DB
MedFile medfile = _cartellaBLL.GetMedFileByFileId(medFileId);
// update it with values taken from the web form
TryUpdateModel(medfile);
// save the updated med file
if (ModelState.IsValid) {
_cartellaBLL.UpdateFile(medfile);
}
...
}
As known, the above TryUpdateModel(medfile) auto-magically validates, parses and converts the fields in the web form updating the passed medfile variable.
In particular, it validates and converts the value of the TextBox2 according to the date format of the application's culture possibly set in the web.config file:
<globalization culture="it-IT" uiCulture="it-IT" />
My problem is that I'd like the user would be able to set the date in the webform using one of two possible formats: the one of the default culture, in my case dd/MM/yyyy (Italy), and the international yyyy-MM-dd (ISO 8601).
Is it possible to instruct TryUpdateModel(TModel) to 'accept' both the format?
Related
I am trying to bind an ASP DataList control with the values returned from an XML file. What's somewhat unique is that I'm not loading the XML from a file, but rather using XMLTextReader() to load it as a string. The reason for this is that the XML will be built from values read from the database. Here's the code which takes (in this case a hard-coded) XML string, adds it to a DataSet and then binds the DataList control...
StringBuilder xml = new StringBuilder();
xml.Append("<product>");
xml.Append("<sku>241</sku>");
xml.Append("<prodID>2SIDED</prodID>");
xml.Append("<name>Product Name</name>");
xml.Append("<price>6.99</price>");
xml.Append("<description>Product Description</description>");
xml.Append("<standalone>1</standalone>");
xml.Append("<sellable>1</sellable>");
xml.Append("<product-type>10</product-type>");
xml.Append("<customization>");
xml.Append("<option1></option1>");
xml.Append("<option2></option2>");
xml.Append("<option3></option3>");
xml.Append("</customization>");
xml.Append("</product>");
using (XmlTextReader tr = new XmlTextReader(new StringReader(xml.ToString())))
{
var document = XElement.Load(tr);
string source = document.ToString();
DataSet dsProdList = new DataSet();
dsProdList.ReadXml(new StringReader(source));
prodDetail.DataSource = dsProdList;
prodDetail.DataBind();
}
Here's the DataList control...
<asp:DataList ID="prodDetail" runat="server" OnItemDataBound="prodDetail_ItemDataBound">
<ItemTemplate>
<div class="proddetail">
<asp:Image ID="Image" runat="server" width="480" height="325" AlternateText='<%#DataBinder.Eval(Container.DataItem, "name") %>'/>
<asp:HiddenField ID="hdnStandalone" runat="server" Value='<%#DataBinder.Eval(Container.DataItem, "standalone") %>' Visible="false" />
<asp:HiddenField ID="hdnSellable" runat="server" Value='<%#DataBinder.Eval(Container.DataItem, "sellable") %>' Visible="false" />
<asp:HiddenField ID="hdnTypeId" runat="server" Value='<%#DataBinder.Eval(Container.DataItem, "product-type") %>' Visible="false" />
<asp:HiddenField ID="hdnOption1" runat="server" Value='<%# DataBinder.Eval(Container.DataItem, "option1") %>' Visible="false" />
<asp:HiddenField ID="hdnOption2" runat="server" Value='<%#DataBinder.Eval(Container.DataItem, "option2") %>' Visible="false" />
<asp:HiddenField ID="hdnOption3" runat="server" Value='<%#DataBinder.Eval(Container.DataItem, "option3") %>' Visible="false" />
<asp:Label ID="lblDescription" runat="server" Text='<%#DataBinder.Eval(Container.DataItem, "description") %>'>
</div>
</ItemTemplate>
</asp:DataList>
This seems to be working fine until the code attempts to bind "option1" at that point I get the following exception:
DataBinding: 'System.Data.DataRowView' does not contain a property with the name 'option1'.
From what I can work out this definitely seems to be an issue with "option1" being a child of "customization". If I simply comment out the opening and closing "customization" tags, which effectively leaves the "option(s)" as children of "product" the code runs fine and I get the output I'm expecting.
Is there any way I can format the DataBinder.Eval() to see the child item? If so, I can't figure it out and hours of searching having been unsuccessful. Or should I be tackling this differently? Perhaps not using a DataSet? Any help is appreciated. Thanks.
You can try with xDoc and linq and anonymous type as,
prodDetail.DataSource = from item in xDoc.Descendants("product")
from needThis in item.Descendants("customization")
select new
{ ProductName = item.Element("sku").Value,
ID = item.Element("prodID").Value,
//----other properties----
Option1 = needThis.Element("option1").Value,
Option2 = needThis.Element("option2").Value,
//---and some more properties----
};
you have to make sure you give the property names of the anonymous object same as the property names you are expecting in the databind in datalist.
I am developing a small shopping cart website in asp.net and c#. My problem is in the checkout page I want to display the total price of each product by calculating adding tax to price. I have a datalist which has an ItemTemplate as label for total where I want to bind function call CalculateTotal(price, tax). In database, price has Varchar(MAX) and tax has float datatype. When I tried I got below error:
Server Error in '/' Application.
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: CS1502: The best overloaded method match for 'ProgearHire.Hire.CalculateTotal(string, string)' has some invalid arguments
Source Error:
Line 232:
Line 233:
Line 234: ' runat="server" />
Line 235:
Line 236:
The code which I used is below:
<td align="center">
<asp:Label ID="lbTotal" runat="server" Text=""></asp:Label>
<asp:Label Visible="false" ID="Label9" Value='<%#(CalculateTotal(Eval("Price"), Eval("Tax"))) %>' runat="server" />
</td>
Function:
public float CalculateTotal(string x, string y)
{
p = Convert.ToInt32(x);
q = Convert.ToInt32(y);
return (float)p * (float)q;
}
Can anybody help me in find out the problem. Thanks in advance.
dear friend your code is doing well but the lable control have no value property your have to make your lable to text property so make your code like the bellow
<td align="center">
<asp:Label ID="lbTotal" runat="server" Text=""></asp:Label>
<asp:Label Visible="false" ID="Label9" Text='<%#(CalculateTotal(Eval("Price"), Eval("Tax"))) %>' runat="server" />
</td>
Your method CalculateTotal(string x, string y) is expecting two string arguments, but you are supplying objects as the Eval() method returns object. Correct as follows:
... Value='<%# CalculateTotal(Eval("Price") as string, Eval("Tax") as string) %>'
I'd suggest casting each parameter to a string, Eval returns object. As below:
<asp:Label Visible="false" ID="Label9" Value='<%#(CalculateTotal((string)Eval("Price"), (string)Eval("Tax"))) %>' runat="server" />
You have given wrong attribute for label. It would be "Text" instead of "Value"
<asp:Label Visible="false" ID="Label9" Value='<%#(CalculateTotal(Eval("Price"), Eval("Tax"))) %>' runat="server" />
Replace with this
<asp:Label Visible="false" ID="Label9" Text='<%# CalculateTotal(Convert.ToString(Eval("Price")), Convert.ToString(Eval("Tax"))) %>' runat="server" />
Your error will solve. Also, in the Calculate function you have convert the string to int and return as float. This is also wrong as the tax might be in a decimal format. Please do check that thing
Change your function as below.
public Double CalculateTotal(string x, string y)
{
Double p = Convert.ToDouble(x);
Double q = Convert.ToDouble(y);
return (p * q);
}
The code looks great..
<asp:Label Visible="false" ID="Label9" Text='<%# CalculateTotal(Convert.ToString(Eval("Price")), Convert.ToString(Eval("Tax"))) %>' runat="server" />
Try the function like this..
public Double CalculateTotal(object x, object y)
{
Double p = Convert.ToDouble(x);
Double q = Convert.ToDouble(y);
return (p * q);
}
It is working for me. Happy coding.
I have designed a dropdownlist for the entry of date. Now I have to convert it into text format (like the way you enter into a text field - mm-dd-yyyy) so that I can display it in an xml file.
Any suggestions on how to go about it?
My frontend code looks like this. This is just one part of it. I have 3 more entities like this.:
<td>
LICENSE FROM *
</td>
<td>
<asp:DropDownList ID="drpmm0" runat="server" CssClass="drp1">
</asp:DropDownList>
<asp:DropDownList ID="drpdte0" runat="server" CssClass="drp1">
</asp:DropDownList>
<asp:DropDownList ID="drpyyyy0" runat="server" CssClass="drp1">
</asp:DropDownList>
(mm-dd-yyyy)
<asp:RequiredFieldValidator ID="reqmm0" runat="server" ControlToValidate="drpmm0" Display="Dynamic"ErrorMessage="Select Month"></asp:RequiredFieldValidator>
<asp:RequiredFieldValidator ID="reqdte0" runat="server" ControlToValidate="drpdte0" ErrorMessage="Select Date"></asp:RequiredFieldValidator>
<asp:RequiredFieldValidator ID="reqyyyy0" runat="server" ControlToValidate="drpyyyy0" ErrorMessage="Select Year"></asp:RequiredFieldValidator>
</td>
</tr>
I just need a little guidance for backend.
string strdt= drpdte0.SelectedValue+"/"+drpmm0.SelectedValue+"/"+drpyyyy0.SelectedValue;
string formatedDate = strdt.ToString("dd-MM-yyyy");
To get into string:
string myDate = String.Format("{0}-{1}-{2}", drmm0.SelectedValue, drpdte0.SelectedValue, drpyyy0);
To get into DateTime:
DateTime myDate = new DateTime(Convert.ToInt32(drpyyyy0.SelectedValue)), Convert.ToInt32(drpmm0.SelectedValue),Convert.ToInt32(drpdte0.SelectedValue)));
Format DateTime:
string myDate = String.Format("{0:MM-dd-yyyy}", myDate);
Why don't you use DateTimePicker?
Hi I have created user control for re-sizable text box.
<asp:Panel ID="PanelText" runat="server" CssClass="frameText">
<asp:TextBox runat="server" ID="TextBoxResizable" CssClass="noborder" Width="100%"
Height="100%" TextMode="MultiLine">
</asp:TextBox>
</asp:Panel>
<cc1:ResizableControlExtender ID="ResizableTextBoxExtender" runat="server" TargetControlID="PanelText"
ResizableCssClass="resizingText" HandleCssClass="handleText" OnClientResizing="OnClientResizeText" />
And have created Validator property for this control like:
[ValidationProperty("Text")]
public partial class ResizableTextBoxControl : System.Web.UI.UserControl
{ public string Validator
{
get { return this.TextBoxResizable.Text; }
}
protected void Page_Load(object sender, EventArgs e)
{
}
}
In aspx page I am using this control like:
<uc1:ResizableTextBoxControl ID="tbDescription" MinimumHeight="50" MinimumWidth="100"
MaximumHeight="300" MaximumWidth="400" runat="server" onKeyPress="javascript:Count(this,1500);" onKeyUp="javascript:Count(this,1500);" ValidationGroup="vgSubmit" ></uc1:ResizableTextBoxControl>
<asp:RequiredFieldValidator ID="rfvDescription" runat="server" controlToValidate="tbDescription" ValidationGroup="vgSubmit" ErrorMessage="Description" Text="*" ForeColor="Red" SetFocusOnError="True"></asp:RequiredFieldValidator>
When I click on submit, "tbDescription" does not appear to be mandatory.
What can be wrong with the code?
EDIT
Ok...I got what was the problem, one control was hidden, and required field validator for that control was not disabled, I did it using jquery and now everything is fine except asterics.. I dont understand why asterics are not visible..
try placing your validator to your controlle especially if you just try to validate one textbox
<asp:Panel ID="PanelText" runat="server" CssClass="frameText">
<asp:TextBox runat="server" ID="TextBoxResizable" CssClass="noborder" Width="100%"
Height="100%" TextMode="MultiLine">
</asp:TextBox>
<asp:RequiredFieldValidator
ID="rfvDescription" runat="server" controlToValidate="TextBoxResizable"
ValidationGroup="vgSubmit"
ErrorMessage="Description" Text="*"
ForeColor="Red" SetFocusOnError="True">
</asp:RequiredFieldValidator
</asp:Panel>
<cc1:ResizableControlExtender ID="ResizableTextBoxExtender"
runat="server" TargetControlID="PanelText"
ResizableCssClass="resizingText" HandleCssClass="handleText OnClientResizing="OnClientResizeText" />
in to the user controller it might not be recognized after the page is rendered.
try using Page.IsValid in your Submit button event.
if (!Page.IsValid) {
return;
}
Sorry for all the trouble,
There was one control on page which was hidden and required field validator for that control was not disabled. I disabled it using jQuery like
$(document).ready(function () {
if (!$("#<%=TextBoxResizable.ClientID %>").is(":visible")) {
ValidatorEnable(<%=rfvTextBoxResizable.ClientID %>, false);
}
})
Asteric is visible after placing required field validator outside Panel.
I am getting the following error, Using asp.net and nHibernate.
Databinding methods such as Eval(), XPath(), and Bind() can only be used in the context of a databound control.
I have this listview
<asp:ListView ID="CurrentHourList" runat="server" ItemPlaceholderID="itemPlaceholder">
<LayoutTemplate>
<asp:PlaceHolder ID="itemPlaceholder" runat="server"></asp:PlaceHolder>
</LayoutTemplate>
<ItemTemplate>
<asp:ImageButton ID="DeleteDateButton" CausesValidation="false" runat="server" CommandName="Delete"
ImageUrl="img/delete.png" />
<span style="display: none">
<asp:Label ID="Id" runat="server" Text='<%# Eval("Id") %>'></asp:Label></span>
<asp:Label ID="Date" Text='<%# Eval("Date", "{0:dd MMM yyyy}") %>' runat="server"></asp:Label>
<asp:DropDownList ID="MedicalType" runat="server" SelectedValue='<%# Eval("MedicalType.Id") %>'>
<asp:ListItem Text="Paid" Value="1"></asp:ListItem>
<asp:ListItem Text="Unpaid" Value="2"></asp:ListItem>
<asp:ListItem Text="Special" Value="3"></asp:ListItem>
</asp:DropDownList>
Half-Day:<asp:CheckBox ID="HalfDay" runat="server" Checked='<%# Eval("IsHalfDay") %>' />
<br />
</ItemTemplate>
</asp:ListView>
and this in my code behind
private void BindData(string id)
{
MedLeaveHelper = new MedicalLeaveHelper();
DTO.MedLeaveDTO dto = MedLeaveHelper.GetMedicalRequest(id);
if (dto != null)
{
EnableForm();
this.RequestId.Text = dto.Id.ToString();
this.ddlEmployeeName.SelectedItem.Text = dto.User;
this.Note.Text = dto.Note;
this.CurrentHourList.DataSource = MedLeaveHelper.MakeMedicalDays(id);
this.CurrentHourList.DataBind();
}
MakeMedicalDays(id) simply looks like this. MedicalDays is a IList
internal IEnumerable MakeMedicalDays(string id)
{
int theId = 0;
if (int.TryParse(id, out theId))
{
MedicalRequest r = MedicalRequest.Get(theId);
return r.MedicalDays;
}
return null;
}
When I get to the DataBind() call the error shows up. I've poked around on the tubes but nothing concrete is jumping out at me. I've tried changing the syntax to something like this
DataBinder.Eval(Container.DataItem,"id")
and the error goes away but no data makes it into my ListView either.
as I understand it DataBinder.Eval uses reflection to determine my datatype, but I am not sure how to troubleshoot this issue. Any help you could provide would be great.
Thanks
Jim
Not sure if the problem is in your listview. I tried a simple repro using the following databinding code - which worked fine with the ASPX you included above:
this.CurrentHourList.DataSource = new[] { new { Id = 1, Date = DateTime.Now, MedicalType = new { Id = 1 }, IsHalfDay = false }, new { Id = 1, Date = DateTime.Now, MedicalType = new { Id = 1 }, IsHalfDay = false } };
this.CurrentHourList.DataBind();
Is it possible that the binding error is coming from a different control (ie. not inside of the listview?)
If you need to use declarative databinding on a control or property which doesn't support it, you can also look into building your own custom expression builder.