Category Archives: DynamicEntity

DynamicEntity

[RESOLVED]Multiline textbox in Formview with DynamicDataTemplatesCS

Using model binding with the above like so:

<asp:FormView runat="server" ID="ConversationForm" DefaultMode="Edit"
		OnCallingDataMethods="ConversationForm_CallingDataMethods"
		ItemType="MyApp.Model.Conversation"
		DataKeyNames="ConversationID"
		SelectMethod="GetConversation"
		UpdateMethod="UpdateConversation"
		OnItemUpdated="Conversation_ItemUpdated">
		<EditItemTemplate>
			<fieldset>
				<legend>Conversation Notes:</legend>
				<ol>
					<asp:DynamicEntity runat="server" Mode="Edit" />
				</ol>
			</fieldset>
			<asp:Button ID="btnUpdate" runat="server" Text="Save" CommandName="Update" />
			<asp:Button ID="btnCancel" runat="server" Text="Cancel" CausesValidation="false" OnClick="btnCancel_Click" />
		</EditItemTemplate>
	</asp:FormView>

The Conversation entity basically has one property, "Text", which should contain freeform text captured by the user.

The DynamicEntity control generates a simple textbox for this property as it has a datatype of string.

How do I tell it to create a multiline textbox instead?

Can I add some sort of data annotation to the Conversation class that will tell the Dynamic Templates to create a multiline textbox?

hi,

It does not seem to be possible.

Please spend little time to look at the following link

http://stackoverflow.com/questions/16840179/multiline-textbox-in-formview-with-dynamicdatatemplatescs

Best Regards

 

Yip, that is my own post on Stackoverflow as nobody here on the Asp.Net seemed to know. 

check this out. 

http://forums.asp.net/t/1646665.aspx/1

all you need to do is to use UIHint attribute on your model properties. 

Regards

Faraz

[RESOLVED]The field template folder '~/DynamicData/EntityTemplates/' does not exist.

Hi,

I try to make a dynamic FormView for insert data but a get this error: "The field template folder ‘~/DynamicData/EntityTemplates/’ does not exist. "

My code:

<asp:FormView ID="FormViewDocumento" DefaultMode="Insert" ItemType="BE.Documento"  runat="server" BackColor="White" BorderColor="#999999" BorderStyle="Solid" BorderWidth="1px" CellPadding="3" ForeColor="Black" GridLines="Vertical">
            <InsertItemTemplate>
                <fieldset class="form-horizontal">
                    <legend>Nuevo documento</legend>
                    <asp:DynamicEntity ID="DynamicEntity1" runat="server" Mode="Insert"></asp:DynamicEntity>
                    
                </fieldset>
            </InsertItemTemplate>
            <EditRowStyle BackColor="#000099" Font-Bold="True" ForeColor="White" />
            <FooterStyle BackColor="#CCCCCC" />
            <HeaderStyle BackColor="Black" Font-Bold="True" ForeColor="White" />
            <PagerStyle BackColor="#999999" ForeColor="Black" HorizontalAlign="Center" />
        </asp:FormView>

Many thanks.

Regards

hi fabrizotus,

During the load stage of the ASP.NET page lifecycle, DynamicEntity control finds the appropriate user control in the
EntityTemplates folder of the Dynamic Data application and dynamically creates it to provide entity-specific portion of the page.

here is a detailed
tutorial:

Understanding ASP.NET Dynamic Data: Entity Templates

http://www.olegsych.com/2010/09/understanding-aspnet-dynamic-data-entity-templates/

http://msdn.microsoft.com/en-us/library/ee211433(v=vs.100).aspx#entity_templates

If you have any questions please do not hesitate to contact me.

[RESOLVED]Find value of a dynamic control from a formview

I have created a dynamically created FromView which contains a list of user details.

<asp:Panel ID="DetailsPanel" runat="server" CssClass="formview">
<br />
<asp:FormView ID="FormView1" runat="server" DataSourceID="DetailsDataSource" RenderOuterTable="false"
OnPreRender="FormView1_PreRender" OnModeChanging="FormView1_ModeChanging" OnItemUpdated="FormView1_ItemUpdated"
OnItemInserted="FormView1_ItemInserted" OnItemDeleted="FormView1_ItemDeleted" OnItemCommand="FormView1_ItemCommand">
<HeaderTemplate>
<table id="detailsTable" class="DDDetailsTable" cellpadding="6" />
</HeaderTemplate>
<ItemTemplate>
<tr class="td">
<td class="DDLightHeader">Order No</td>
<td><asp:DynamicControl ID="OrderNo" runat="server" DataField="OrderNo" /></td>
</tr>
<tr class="td">
<td class="DDLightHeader">User ID</td>
<td><asp:DynamicControl runat="server" DataField="UserID" /></td>
</tr>
<tr class="td">
<td class="DDLightHeader">Display Name</td>
<td><asp:DynamicControl runat="server" DataField="DisplayName" /></td>
</tr>
<tr class="td">
<td class="DDLightHeader">Email Address</td>
<td><asp:DynamicControl ID="EmailAddress" runat="server" DataField="EmailAddress" /></td>
</tr>
<tr class="td">
<td class="DDLightHeader">Project Code</td>
<td><asp:DynamicControl runat="server" DataField="ProjectCode" /></td>
</tr>
<tr class="td">
<td class="DDLightHeader">Event Description</td>
<td><asp:DynamicControl runat="server" DataField="EventDesc" /></td>
</tr>
<tr class="td">
<td class="DDLightHeader">Delivery Date</td>
<td><asp:DynamicControl runat="server" DataField="DeliveryDate" /></td>
</tr>
<tr class="td">
<td class="DDLightHeader">Date Ordered</td>
<td><asp:DynamicControl runat="server" DataField="DateOrdered" /></td>
</tr>
<tr class="td">
<td class="DDLightHeader">Site</td>
<td><asp:DynamicControl runat="server" DataField="Site" /></td>
</tr>
<tr class="td">
<td class="DDLightHeader">Time</td>
<td><asp:DynamicControl runat="server" DataField="Time" /></td>
</tr>
<tr class="td">
<td class="DDLightHeader">Time Room is Available</td>
<td><asp:DynamicControl ID="DynamicControl1" runat="server" DataField="TimeRoomAvailable" Mode="ReadOnly" /></td>
</tr>
<tr class="td">
<td class="DDLightHeader">Time Room to be Cleared</td>
<td><asp:DynamicControl ID="DynamicControl2" runat="server" DataField="TimeCleared" Mode="ReadOnly" /></td>
</tr>
<tr class="td">
<td class="DDLightHeader">Location</td>
<td><asp:DynamicControl runat="server" DataField="Location" /></td>
</tr>
<tr class="td">
<td class="DDLightHeader">Additional Information</td>
<td><asp:DynamicControl runat="server" ID="AdditionalInfo" DataField="AdditionalInfo" /></td>
</tr>
<tr class="td">
<td class="DDLightHeader">Item Costs</td>
<td><asp:DynamicControl runat="server" ID="ItemCosts" DataField="ItemCosts" /></td>
</tr>
<tr class="td">
<td class="DDLightHeader">AdditionalCosts</td>
<td><asp:DynamicControl runat="server" ID="AdditionalCosts" DataField="AdditionalCosts" /></td>
</tr>
<tr class="td">
<td class="DDLightHeader">Total Costs</td>
<td><asp:DynamicControl runat="server" DataField="TotalCosts" /></td>
</tr>
<tr class="td">
<td class="DDLightHeader">More Information Required</td>
<td><asp:DynamicControl runat="server" DataField="MoreInformationRequired" UIHint="MultilineText" /></td>
</tr>
<tr class="td">
<td class="DDLightHeader">Reason Rejected</td>
<td><asp:DynamicControl runat="server" DataField="ReasonRejected" UIHint="MultilineText" /></td>
</tr>
<tr class="td">
<td class="DDLightHeader">Order Progress</td>
<td><asp:DynamicControl runat="server" DataField="OrderProgress" /></td>
</tr>
<tr class="td">
<td class="DDLightHeader">Imported Into Dream</td>
<td><asp:DynamicControl runat="server" DataField="ImportedIntoDream" /></td>
</tr>
<tr class="td">
<td colspan="2">
<asp:LinkButton ID="LinkButton1" runat="server" CommandName="Edit" Text="Edit" />
<asp:LinkButton ID="LinkButton2" runat="server" CommandName="Delete" Text="Delete"
OnClientClick='return confirm("Are you sure you want to delete this item?");' />
</td>
</tr>
</ItemTemplate>
<EditItemTemplate>
<tr class="td">
<td class="DDLightHeader">Order No</td>
<td><asp:DynamicControl ID="OrderNo" runat="server" DataField="OrderNo" Mode="ReadOnly"/></td>
</tr>
<tr class="td">
<td class="DDLightHeader">User ID</td>
<td><asp:DynamicControl runat="server" DataField="UserID" Mode="ReadOnly"/></td>
</tr>
<tr class="td">
<td class="DDLightHeader">Display Name</td>
<td><asp:DynamicControl runat="server" DataField="DisplayName" Mode="ReadOnly" /></td>

</tr>
<tr class="td">
<td class="DDLightHeader">Email Address</td>
<td><asp:DynamicControl runat="server" DataField="EmailAddress" ID="Email"/></td>
</tr>
<tr class="td">
<td class="DDLightHeader">Project Code</td>
<td><asp:DynamicControl runat="server" DataField="ProjectCode" Mode="ReadOnly" /></td>
</tr>
<tr class="td">
<td class="DDLightHeader">Event Description</td>
<td><asp:DynamicControl runat="server" DataField="EventDesc" Mode="ReadOnly" /></td>
</tr>
<tr class="td">
<td class="DDLightHeader">Delivery Date</td>
<td><asp:DynamicControl runat="server" DataField="DeliveryDate" Mode="ReadOnly" /></td>
</tr>
<tr class="td">
<td class="DDLightHeader">Date Ordered</td>
<td><asp:DynamicControl runat="server" DataField="DateOrdered" Mode="ReadOnly" /></td>
</tr>
<tr class="td">
<td class="DDLightHeader">Site</td>
<td><asp:DynamicControl runat="server" DataField="Site" Mode="ReadOnly" /></td>
</tr>
<tr class="td">
<td class="DDLightHeader">Time</td>
<td><asp:DynamicControl runat="server" DataField="Time" Mode="ReadOnly" /></td>
</tr>
<tr class="td">
<td class="DDLightHeader">Time Room is Available</td>
<td><asp:DynamicControl ID="DynamicControl1" runat="server" DataField="TimeRoomAvailable" Mode="ReadOnly" /></td>
</tr>
<tr class="td">
<td class="DDLightHeader">Time Room to be Cleared</td>
<td><asp:DynamicControl ID="DynamicControl2" runat="server" DataField="TimeCleared" Mode="ReadOnly" /></td>
</tr>
<tr class="td">
<td class="DDLightHeader">Location</td>
<td><asp:DynamicControl runat="server" DataField="Location" Mode="ReadOnly" /></td>
</tr>
<tr class="td">
<td class="DDLightHeader">Additional Information</td>
<td><asp:DynamicControl runat="server" DataField="AdditionalInfo" Mode="ReadOnly" /></td>
</tr>
<tr class="td">
<td class="DDLightHeader">Item Costs</td>
<td><asp:DynamicControl runat="server" ID="ItemCosts" DataField="ItemCosts" Mode="Edit" /></td>
</tr>
<tr class="td">
<td class="DDLightHeader">Additional Costs</td>
<td><asp:DynamicControl runat="server" ID="AdditionalCosts" DataField="AdditionalCosts" Mode="Edit" /></td>
</tr>
<tr class="td">
<td class="DDLightHeader">Total Costs</td>
<td><asp:DynamicControl runat="server" ID="TotalCosts" DataField="TotalCosts" Mode="Edit" /></td>
</tr>

<tr class="td">
<td class="DDLightHeader">More Information Required</td>
<td><asp:DynamicControl runat="server" DataField="MoreInformationRequired" Mode="Edit" UIHint="MultilineText" /></td>
</tr>
<tr class="td">
<td class="DDLightHeader">Reason Rejected</td>
<td><asp:DynamicControl runat="server" DataField="ReasonRejected" Mode="Edit" UIHint="MultilineText" /></td>
</tr>
<tr class="td">
<td class="DDLightHeader">Order Progress</td>
<td><asp:DynamicControl runat="server" DataField="OrderProgress" Mode="Edit" UIHint="OrderProgressDropDown" /></td>
</tr>
<tr class="td">
<td class="DDLightHeader">Imported Into Dream</td>
<td><asp:DynamicControl runat="server" DataField="ImportedIntoDream" Mode="Edit" /></td>
</tr>

<tr class="td">
<td colspan="2">
<asp:LinkButton ID="LinkButton4" runat="server" CommandName="Update" Text="Update" />
<asp:LinkButton ID="LinkButton5" runat="server" CommandName="Cancel" Text="Cancel" CausesValidation="false" />
</td>
</tr>
</EditItemTemplate>
<InsertItemTemplate>
<asp:DynamicEntity ID="DynamicEntity3" runat="server" Mode="Insert" />
<tr class="td">
<td colspan="2">
<asp:LinkButton ID="LinkButton6" runat="server" CommandName="Insert" Text="Insert" />
<asp:LinkButton ID="LinkButton7" runat="server" CommandName="Cancel" Text="Cancel" CausesValidation="false" />
</td>
</tr>
</InsertItemTemplate>
<FooterTemplate>
</table>
</FooterTemplate>
</asp:FormView>

I’d like to be able to email the user, based on the email address in the formview, when I click update.

I have amended FormView1_Updated in the code behind as follows:

protected void FormView1_ItemUpdated(object sender, FormViewUpdatedEventArgs e)
{
string id = e.Keys["OrderNo"].ToString();


// I have tried this
//string email = FormView1.FindControl("EmailAddress").ToString();

//I have also tried this
//DynamicControl emailadd = ((DynamicControl)FormView1.FindControl("Email"));
//string email = emailadd.ToString();

GridView1.DataBind();
MailMessage objMail = new MailMessage();
SmtpClient smtpClient = new SmtpClient();
objMail.To.Add(email);
objMail.From = new MailAddress("xxxx@xxxxxxx.xx.xx");
objMail.Subject = "Catering Request";
objMail.IsBodyHtml = true;
objMail.Body = "<html><body>" +
"<p><font face='Verdana' color='#000080' font size='2'>Your catering request, order number " + id + " has been updated by catering. Please view the " +
"<a href='http://dev-catering.bathspa.ac.uk/'>Catering Request System</a> for the details.</font></p>";

smtpClient.Port = xxxx;
smtpClient.Host = "xxxx.xxxxxxxxx.com";

NetworkCredential nc = new NetworkCredential("xxxxxx", "xxxxxxxxxxxxxxxx");
smtpClient.Credentials = nc;
smtpClient.Send(objMail);
}

If I type an email address straight into the objMail.To.Add(email) field this works fine. My problem is that I cannot capture the value of the email address in the FormView. I keep getting a null error. Has the value of the email address already been destroyed
before ‘ItemUpdated’ is called.

Or am I not finding the value am I just finding the control. If so how do I find the value of the dynamically created control.

Many thanks
Claire

The ID of the conrol that holds the email is different between the EditItemTemplate and the ItemTemplate. I suspect that when the Item_Updated event is raised by the FormView, the FormView will be showing it’s ItemTemplate, so you should look for the control
with ID= "EmailAddress" not "Email".

Also, regarding getting the value of the row key using this code that you wrote at the begging of the method:

string id = e.Keys["OrderNo"].ToString(); 

This will not work untill you set the FormView DataKeyNames proeprty to the name of the primiary key column as below:

<asp:FormView ID="…… "  DataKeyNames="OrderNo"</div> <div>After doing this, the e.Keys["OrderNo"] should return the correct value which you can use later on the query the database and
get the email address if you fail to get it from the FormView dynamic contorl.

Hi Anas

Thank you so much for this (and apologies for taking so long to reply. I had to work on something else).  I wasn’t sure which ID the Item_Updated event was using so that’s why they were different. I tried using "Email" and "EmailAddress" but I couldn’t get
either of these to work. However I did try your suggestion of using the orderID to query the database so this is what I have done for sending an email in the ItemUpdated event. Thank you so much (I was banging my head against the wall on this one).

However I’d also like to be able to send an email when the item is deleted (or deleting perhaps). I had added the code to send an email to the FormView1_ItemDeleted event but the row is deleted before the email is sent. So I tried to create a FormView1_ItemDeleting
event and add OnItemDeleting="FormView1_ItemDeleting" to the FormView1 source code ie

<asp:FormView ID="FormView1" runat="server" DataSourceID="DetailsDataSource" RenderOuterTable="false" DataKeyNames="OrderNo"
OnPreRender="FormView1_PreRender" OnModeChanging="FormView1_ModeChanging" OnItemUpdated="FormView1_ItemUpdated"
OnItemInserted="FormView1_ItemInserted" OnItemDeleted="FormView1_ItemDeleted" OnItemDeleting="FormView1_ItemDeleting"
OnItemCommand="FormView1_ItemCommand">

However when I run the project I am getting the error error CS0123: No overload for ‘FormView1_ItemDeleting’ matches delegate ‘System.Web.UI.WebControls.FormViewDeleteEventHandler’

Do you have any idea how I can add my code to send an email when deleting a row?

Many thanks
Claire 

coxy16

However when I run the project I am getting the error error CS0123: No overload for ‘FormView1_ItemDeleting’ matches delegate ‘System.Web.UI.WebControls.FormViewDeleteEventHandler’

Make sure you have the following signature for the "FormView1_ItemDeleting" function (check in code behind):

protected void FormView1_ItemDeleting(object sender, FormViewDeleteEventArgs e)
        {

        }

Thank you again Anas. I should have mentioned that I tried this. I have added OnItemDeleting="FormView1_ITemDeleting" to the source code ie

<asp:FormView ID="FormView1" runat="server" DataSourceID="DetailsDataSource"
                    RenderOuterTable="false" DataKeyNames="OrderNo"
                    OnPreRender="FormView1_PreRender" OnModeChanging="FormView1_ModeChanging" OnItemUpdated="FormView1_ItemUpdated"
                    OnItemInserted="FormView1_ItemInserted"
                    OnItemDeleted="FormView1_ItemDeleted" OnItemCommand="FormView1_ItemCommand" OnItemDeleting="FormView1_ItemDeleting">

And in the code behind I have added 

protected void FormView1_ItemDeleting(object sender, FormViewDeletedEventArgs e)
        {
            string orderNo = e.Keys["OrderNo"].ToString();
            using (SqlConnection orderConnection = new SqlConnection(ConfigurationManager.ConnectionStrings["cateringConnectionString"].ConnectionString))
            {
                SqlCommand orderCommand = orderConnection.CreateCommand();
                orderConnection.Open();

                orderCommand.CommandText = "SELECT EmailAddress FROM tblCatering WHERE OrderNo = " + orderNo;
                SqlDataReader readerOrder = orderCommand.ExecuteReader();
                if (readerOrder.Read())
                {
                    string emailAddress = readerOrder["EmailAddress"].ToString();
                    readerOrder.Close();

                    GridView1.DataBind();
                    MailMessage objMail = new MailMessage();
                    SmtpClient smtpClient = new SmtpClient();
                    objMail.To.Add(emailAddress);
                    objMail.From = new MailAddress("catering@xxxxxxxxx.xx.xx");
                    objMail.Subject = "Catering Request";
                    objMail.IsBodyHtml = true;
                    objMail.Body = "<html><body>" +
                                "<p><font face='Verdana' color='#000080' font size='2'>Your catering request, order number " + orderNo + ", has been updated by catering. Please view the " +
                                "<a href='http://dev-catering.bathspa.ac.uk/'>Catering Request System</a> for the details.</font></p>";

                    smtpClient.Port = xxxx;
                    smtpClient.Host = "xxxx.xxxxxxx.xxx";

                    NetworkCredential nc = new NetworkCredential("xxxxxxx", "xxxxxxxxxxxxxx");
                    //SmtpClient smtpClient = new SmtpClient("xxxxxxxxx.xxxxxxxx.xx.xx");
                    smtpClient.Credentials = nc;
                    smtpClient.Send(objMail);
                }
            }
        }

However I am getting this error

No overload for ‘FormView1_ItemDeleting’ matches delegate ‘System.Web.UI.WebControls.FormViewDeleteEventHandler’

Is there another reference I need to add somewhere?

Thanks for all your help with this.

coxy16

protected void FormView1_ItemDeleting(object sender, FormViewDeletedEventArgs e)

The singnature is not valid. You are using FormViewDeletedEventArgs and you should use “FormViewDeleteEventArgs” (without the “d”) , please refer to the sample i posted in my previous reply. So we have two different event arguments one for Item deleted and another one for ItemDeleting. 

For ItemDeleting: use FormViewDeleteEventArgs

e.g.

 protected void FormView1_ItemDeleting(object sender, FormViewDeleteEventArgs e)
        {
 
        }

For ItemDeleted: use FormViewDeletedEventArgs

e.g.

protected void FormView1_ItemDeleted(object sender, FormViewDeletedEventArgs e)
        {
 
        }

Thank you, thank you, thank you. I’m so sorry I didn’t spot that. You are a total star. Smile

That has worked. Brilliant. Thanks again for your help.

[RESOLVED]FormView & Model Binding

Hi,

I am using a FormView with ModelBinding in my WebForms application, using VS2012 Pro. I am binding a form to my Db Table with CRUD operations enabled like so:

My FormView:

<asp:ValidationSummary ID="ValidationSummary1" runat="server" ShowModelStateErrors="true" />
<asp:FormView runat="server" ID="addDogForm"
    ItemType="PoochiesPrix.Models.DogInfo"
    InsertMethod="addDogForm_InsertItem" DefaultMode="Insert"
    RenderOuterTable="false" OnItemInserted="addDogForm_ItemInserted">
    <InsertItemTemplate>
        <fieldset>
            <ol>
                <asp:DynamicEntity ID="DynamicEntity1" runat="server" Mode="Insert" />
            </ol>
            <asp:Button ID="btnSave" runat="server" Text="Save" CommandName="Insert" />
            <asp:Button ID="btnCancel" runat="server" Text="Cancel" CausesValidation="false" OnClick="cancelButton_Click" />
        </fieldset>
    </InsertItemTemplate>
</asp:FormView>

Then in my code behind I am I am binding my data using ModelBinding:

public void addDogForm_InsertItem()
        {
            var item = new DogInfo();

            TryUpdateModel(item);
            if (ModelState.IsValid)
            {
                using (PoochiesContext db = new PoochiesContext())
                {
                    db.DogInfoes.Add(item);
                    db.SaveChanges();
                }
            }
        }

Everything is working well, except that on my Model I have two properties that are composite keys in another table that i need to reference

        public int OwnerID { get; set; }
        public int dogTypeID { get; set; }

These two properties are showing up on my From, and I dont want them too. I am using DynamicData so my forms are built from my model dynamically. These properties are showing up on my form as:

OwnerID  //with a textbox to enter text

DogTypeId  //with a textbox to enter text

I dont want to show these on my form. Here is the raw HTML from the page. How can Not return them, or can I use jQuery to hide them? What is the best way to handle this? I do not want any perfomance concerns.

Raw HTML

 <li class="DDLightHeader" style="list-style-type: none;">
            <label for="FeaturedContent_addDogForm_ctl01_ctl13___OwnerID_TextBox1" id="FeaturedContent_addDogForm_ctl01_ctl13_Label1">OwnerID</label>
        </li>
        <li style="list-style-type: none;">
            <input name="ctl00$FeaturedContent$addDogForm$ctl01$ctl13$__OwnerID$TextBox1" type="number" size="10" id="FeaturedContent_addDogForm_ctl01_ctl13___OwnerID_TextBox1" />

<span data-val-controltovalidate="FeaturedContent_addDogForm_ctl01_ctl13___OwnerID_TextBox1" data-val-errormessage="The OwnerID field is required." id="FeaturedContent_addDogForm_ctl01_ctl13___OwnerID_RequiredFieldValidator1" title="The OwnerID field is required." class="DDControl DDValidator" data-val="true" data-val-evaluationfunction="RequiredFieldValidatorEvaluateIsValid" data-val-initialvalue="" style="visibility:hidden;">*</span>
<span data-val-controltovalidate="FeaturedContent_addDogForm_ctl01_ctl13___OwnerID_TextBox1" data-val-errormessage="The field OwnerID must be a valid integer." id="FeaturedContent_addDogForm_ctl01_ctl13___OwnerID_CompareValidator1" title="The field OwnerID must be a valid integer." class="DDControl DDValidator" data-val="true" data-val-type="Integer" data-val-evaluationfunction="CompareValidatorEvaluateIsValid" data-val-operator="DataTypeCheck" style="visibility:hidden;">*</span>
<span data-val-controltovalidate="FeaturedContent_addDogForm_ctl01_ctl13___OwnerID_TextBox1" data-val-enabled="False" id="FeaturedContent_addDogForm_ctl01_ctl13___OwnerID_RegularExpressionValidator1" class="DDControl DDValidator" data-val="true" data-val-evaluationfunction="RegularExpressionValidatorEvaluateIsValid" style="visibility:hidden;">*</span>
<span data-val-controltovalidate="FeaturedContent_addDogForm_ctl01_ctl13___OwnerID_TextBox1" data-val-enabled="False" id="FeaturedContent_addDogForm_ctl01_ctl13___OwnerID_RangeValidator1" class="DDControl DDValidator" data-val="true" data-val-type="Integer" data-val-evaluationfunction="RangeValidatorEvaluateIsValid" data-val-maximumvalue="100" data-val-minimumvalue="0" style="visibility:hidden;">*</span>
<span data-val-controltovalidate="FeaturedContent_addDogForm_ctl01_ctl13___OwnerID_TextBox1" id="FeaturedContent_addDogForm_ctl01_ctl13___OwnerID_DynamicValidator1" class="DDControl DDValidator" data-val="true" style="visibility:hidden;">*</span>


        </li>
    
           <li class="DDLightHeader" style="list-style-type: none;">
            <label for="FeaturedContent_addDogForm_ctl01_ctl14___dogTypeID_TextBox1" id="FeaturedContent_addDogForm_ctl01_ctl14_Label1">dogTypeID</label>
        </li>
        <li style="list-style-type: none;">
            <input name="ctl00$FeaturedContent$addDogForm$ctl01$ctl14$__dogTypeID$TextBox1" type="number" size="10" id="FeaturedContent_addDogForm_ctl01_ctl14___dogTypeID_TextBox1" />

<span data-val-controltovalidate="FeaturedContent_addDogForm_ctl01_ctl14___dogTypeID_TextBox1" data-val-errormessage="The dogTypeID field is required." id="FeaturedContent_addDogForm_ctl01_ctl14___dogTypeID_RequiredFieldValidator1" title="The dogTypeID field is required." class="DDControl DDValidator" data-val="true" data-val-evaluationfunction="RequiredFieldValidatorEvaluateIsValid" data-val-initialvalue="" style="visibility:hidden;">*</span>
<span data-val-controltovalidate="FeaturedContent_addDogForm_ctl01_ctl14___dogTypeID_TextBox1" data-val-errormessage="The field dogTypeID must be a valid integer." id="FeaturedContent_addDogForm_ctl01_ctl14___dogTypeID_CompareValidator1" title="The field dogTypeID must be a valid integer." class="DDControl DDValidator" data-val="true" data-val-type="Integer" data-val-evaluationfunction="CompareValidatorEvaluateIsValid" data-val-operator="DataTypeCheck" style="visibility:hidden;">*</span>
<span data-val-controltovalidate="FeaturedContent_addDogForm_ctl01_ctl14___dogTypeID_TextBox1" data-val-enabled="False" id="FeaturedContent_addDogForm_ctl01_ctl14___dogTypeID_RegularExpressionValidator1" class="DDControl DDValidator" data-val="true" data-val-evaluationfunction="RegularExpressionValidatorEvaluateIsValid" style="visibility:hidden;">*</span>
<span data-val-controltovalidate="FeaturedContent_addDogForm_ctl01_ctl14___dogTypeID_TextBox1" data-val-enabled="False" id="FeaturedContent_addDogForm_ctl01_ctl14___dogTypeID_RangeValidator1" class="DDControl DDValidator" data-val="true" data-val-type="Integer" data-val-evaluationfunction="RangeValidatorEvaluateIsValid" data-val-maximumvalue="100" data-val-minimumvalue="0" style="visibility:hidden;">*</span>
<span data-val-controltovalidate="FeaturedContent_addDogForm_ctl01_ctl14___dogTypeID_TextBox1" id="FeaturedContent_addDogForm_ctl01_ctl14___dogTypeID_DynamicValidator1" class="DDControl DDValidator" data-val="true" style="visibility:hidden;">*</span>


        </li>
    

Model Binding is a new animal to me, but I would like to get advice on the best way to keep the ID properties from rendering. I though about trying to do it in my code behind, but LINQ is new to me too. Any advice would be great. Thanks.

P.S. Here is my model

 public class DogInfo
    {
        
        [Key, Display(Name= "DogInfoID")]
        [ScaffoldColumn(false)]
        public int DogInfoID { get; set; }
        
        [Required(ErrorMessage="License number is required"),StringLength(15), Display(Name= "License Number")]
        public string licenseNumber { get; set; }

        [Required(ErrorMessage = "A date is required"), Display(Name = "Date License was Renewed")]
        public DateTime dateLicenseRenewed { get; set; }

        [Required(ErrorMessage = "A date is required"), Display(Name = "Date License Expires")]
        public DateTime dateLicenseExpires { get; set; }

        [Required(ErrorMessage="Name is required"), StringLength(35), Display(Name="Dogs Name")]
        public string name { get; set; }

        [Required(ErrorMessage = "Enter Male or Female"), StringLength(6, MinimumLength = 4), Display(Name = "Sex")]
        public string sex { get; set; }

        [Display(Name= "Breed")]
        public string breed { get; set; }

        [Required(ErrorMessage="Required. If you do not know your dogs DOB, enter an approximate date."), Display(Name = "Birth Date") ]
        public DateTime birthDate { get; set; }

        [Display(Name= "Microchip Number")]
        public string microchipNumber { get; set; }

        [Display(Name= "Breed Registration")]
        public string breedRegistration { get; set; }

        [Display(Name= "Coat Color")]
        public string coatColor { get; set; }

        [Display(Name= "Eye Color")]
        public string eyeColor { get; set; }

        [Display(Name = "Breed Shelter Name")]
        public string breedShelterName { get; set; }

        [Display(Name= "Date Acquired")]
        public Nullable<DateTime> dateAcquired { get; set; }

        public int OwnerID { get; set; }
        public int dogTypeID { get; set; }
       
        public virtual Owner Owner { get; set; }
        public virtual Record Record { get; set; }
        public virtual ICollection<DogPic> DogPics { get; set; }
        public virtual ICollection<Record> Records { get; set; }
    }

Hi Mark_F,

Based on your description, my understanding is that you would like to display specify column.

If so, I suggest you using DynamicControl to specify columns, like this:

<InsertItemTemplate>
        <fieldset>
            <ol>
				<asp:DynamicControl runat="server" DataField="YourColumnName" Mode="Insert" />
                <%--<asp:DynamicEntity runat="server" Mode="Insert" />--%>
            </ol>
            <asp:Button runat="server" Text="Insert" CommandName="Insert" />
            <asp:Button runat="server" Text="Cancel" CausesValidation="false" OnClick="cancelButton_Click" />
        </fieldset>
    </InsertItemTemplate>

More information about DynamicControl please refer to:
http://msdn.microsoft.com/en-us/library/system.web.dynamicdata.dynamiccontrol(v=vs.110).aspx

Hope it helps.

Best Regards,
Terry Guo

Hi  Terry,

So, you are saying I can specify which columns I want to display byspecifying them in here:

<fieldset>
            <ol>
                <asp:DynamicEntity ID="DynamicEntity1" runat="server" Mode="Insert" /> //place them here
            </ol>
            <asp:Button ID="btnSave" runat="server" Text="Save" CommandName="Insert" />
            <asp:Button ID="btnCancel" runat="server" Text="Cancel" CausesValidation="false" OnClick="cancelButton_Click" />
        </fieldset>

Do I need to specify each Like this:

<asp:DynamicControl runat="server" DataField="name" Mode="Insert" />
<asp:DynamicControl runat="server" DataField="address" Mode="Insert" />
<asp:DynamicControl runat="server" DataField="date" Mode="Insert" />
<asp:DynamicControl runat="server" DataField="town" Mode="Insert" />
<asp:DynamicControl runat="server" DataField="country" Mode="Insert" />
<asp:DynamicControl runat="server" DataField="email" Mode="Insert" />

//these are just examples, I realize I will have to put the exact name of my Db fields here

Hi Mark_F,

Yes, the DynamicEntity will generate the all column automatically, but when you want to display specify column, you can using the DynamicControl.

Best Regards,
Terry Guo

Great, thanks allot for the information, I just added the fields that I wanted to display like this:

<asp:DynamicControl runat="server" DataField="firstName" Mode="Insert" />
<asp:DynamicControl runat="server" DataField="lastName" Mode="Insert" />
<asp:DynamicControl runat="server" DataField="address" Mode="Insert" />
<asp:DynamicControl runat="server" DataField="city" Mode="Insert" />
<asp:DynamicControl runat="server" DataField="state" Mode="Insert" />
<asp:DynamicControl runat="server" DataField="email" Mode="Insert" />

Thank you, worked perfectly! Cheers!

Adding UserId to table using Model Binding

Hi everyone, I used the preinstalled Web Forms Template (.Net 4.5) and, I have a WebForms application where I’m using Modelbinding, and EntityFramework code first. All is going faily well. I am also using the built in Membership provider to handle Authentication/Authorization.
After my user selects a service from my Services page, I am redirecting them to the Register page, where they will register for an account.

My question is, After they register, I am sending them to a page where they will add their personal info. I am using DynamicDataTemplates with model binding:

//here is my FormView
<div class="container">
        <div class="row">
            <div class="col-md-12">
                <hgroup class="title">
        <h1><%: Title %>.</h1>
        <h2>Use the form below to add your personal info.</h2>
    </hgroup>
            </div><!--end of col-md-12-->
        </div><!--end of row-->
    </div><!--end of container-->
    <div class="clearTop"></div>
</asp:Content>
<asp:Content ID="Content3" ContentPlaceHolderID="MainContent" runat="server">
    <div class ="container">
        <asp:FormView ID="addUserInfoForm" runat="server" ItemType="PoochiesPrix_4.Models.Owner"
        InsertMethod="addUserInfoForm_InsertItem" DefaultMode="Insert"
        RenderOuterTable="false" OnItemInserted="addUserInfoForm_ItemInserted">
        <InsertItemTemplate>
        <fieldset>
            <ol>
                <asp:DynamicEntity ID="DynamicEntity2" runat="server" Mode="Insert" />

            </ol>
            <asp:Button ID="btnSave" runat="server" Text="Save" CommandName="Insert" />
            <asp:Button ID="btnCancel" runat="server" Text="Cancel" CausesValidation="false" OnClick="cancelButton_Click" />
        </fieldset>
    </InsertItemTemplate>
        </asp:FormView>
    </div><!--end of container-->

My code behind that has my strongly typed fileds:

public void addUserInfoForm_InsertItem()
        {
            var item = new PoochiesPrix_4.Models.Owner();
            TryUpdateModel(item);
            if (ModelState.IsValid)
            {
                using (PoochiesPrixContext db = new PoochiesPrixContext())
                {
                    db.Owners.Add(item);
                    db.SaveChanges();
                }

            }
        }
        protected void addUserInfoForm_ItemInserted(object sender, FormViewInsertedEventArgs e)
        {
            Response.Redirect("~/AddDog.aspx");
        }
        protected void cancelButton_Click(object sender, EventArgs e)
        {
            Response.Redirect("~/OurServices.aspx");
        }

Since my users are registered already. How would I access their UserID in order to insert it into my owners table when they submit this form? I am new to LINQ so I am not sure how to go about this. Since I am using EF context classes, I know this ID is available
to me, but, I dont know how to add it to the code above to insert it as this user who is submitting this form. I am looking for a good article to read and learn how to implement this. Any suggestions are welcomed too.

Hi,

According to your description, you want to insert data into entity model. So far as I know, please refer to the simple demo about person below:

var person = new Person { Name = "Adam" };

var db = new YourEFContext();

db.People.Add(person);

db.SaveChanges();

For more information about insert data into entity model, please refer to the link below:

http://www.dotnetcurry.com/showarticle.aspx?ID=619

Hope it’s useful for you.

Best Regards,

Michelle Ge

Hi Michelle, Thank you. I already know how to insert/update data into an entity model. What I am uncertain about is, how I would insert the currently logged in Users UserId that they were assigned after they registered on the registration page?  I am using
the UserId as a foriegn key in this Owners table, Si I would like to include the userId in this insert from this form.

[RESOLVED]Insert UserId Using Form View

Hi everyone, I used the preinstalled Web Forms Template (.Net 4.5) and, I have a WebForms application where I’m using Modelbinding, and EntityFramework code first. All is going faily well. I am also using the built in Membership provider to handle Authentication/Authorization.
After my user selects a service from my Services page, I am redirecting them to the Register page, where they will register for an account.

My question is, After they register, I am sending them to a page where they will add their personal info. I am using DynamicDataTemplates with model binding:

//here is my FormView
<div class="container">
        <div class="row">
            <div class="col-md-12">
                <hgroup class="title">
        <h1><%: Title %>.</h1>
        <h2>Use the form below to add your personal info.</h2>
    </hgroup>
            </div><!--end of col-md-12-->
        </div><!--end of row-->
    </div><!--end of container-->
    <div class="clearTop"></div>
</asp:Content>
<asp:Content ID="Content3" ContentPlaceHolderID="MainContent" runat="server">
    <div class ="container">
        <asp:FormView ID="addUserInfoForm" runat="server" ItemType="PoochiesPrix_4.Models.Owner"
        InsertMethod="addUserInfoForm_InsertItem" DefaultMode="Insert"
        RenderOuterTable="false" OnItemInserted="addUserInfoForm_ItemInserted">
        <InsertItemTemplate>
        <fieldset>
            <ol>
                <asp:DynamicEntity ID="DynamicEntity2" runat="server" Mode="Insert" />

            </ol>
            <asp:Button ID="btnSave" runat="server" Text="Save" CommandName="Insert" />
            <asp:Button ID="btnCancel" runat="server" Text="Cancel" CausesValidation="false" OnClick="cancelButton_Click" />
        </fieldset>
    </InsertItemTemplate>
        </asp:FormView>
    </div><!--end of container-->

My code behind that has my strongly typed fileds:

public void addUserInfoForm_InsertItem()
        {
            var item = new PoochiesPrix_4.Models.Owner();
            TryUpdateModel(item);
            if (ModelState.IsValid)
            {
                using (PoochiesPrixContext db = new PoochiesPrixContext())
                {
                    db.Owners.Add(item);
                    db.SaveChanges();
                }

            }
        }
        protected void addUserInfoForm_ItemInserted(object sender, FormViewInsertedEventArgs e)
        {
            Response.Redirect("~/AddDog.aspx");
        }
        protected void cancelButton_Click(object sender, EventArgs e)
        {
            Response.Redirect("~/OurServices.aspx");
        }

Since my users are registered already. How would I access their UserID in order to insert it into my owners table when they submit this form? I am new to LINQ so I am not sure how to go about this. Since I am using EF context classes, I know this ID is available
to me, but, I dont know how to add it to the code above to insert it as this user who is submitting this form. I am looking for a good article to read and learn how to implement this. Any suggestions are welcomed too

Hi Mark_F 

MembershipUser mu = Membership.GetUser("username");
string userId = mu.ProviderUserKey.ToString();

For currently logged in user you could use without passing the username;

string userId = Membership.GetUser().ProviderUserKey.ToString();

Hi anujm

Where would this go in my insert method? Im not familiar with using LINQ to insert?

Hi anuj_koundal,

How would I go about this with LINQ? So far I am trying this:

public void addUserInfoForm_InsertItem()
        {  
            string userId = Membership.GetUser().ProviderUserKey.ToString();
            var item = new PoochiesPrix_4.Models.Owner();
            TryUpdateModel(item);
            if (ModelState.IsValid)
            {
                using (PoochiesPrixContext db = new PoochiesPrixContext())
                {
                    db.Owners.Add(item.OwnerID = );
                    db.Owners.Add();
                    db.SaveChanges();
                }

But, I am not sure how to go about it.

Hi Mark_f Do like this

MembershipUser mu = Membership.GetUser("username");
string userId = mu.ProviderUserKey.ToString();

using (PoochiesPrixContext db = new PoochiesPrixContext())
                {
                    //==== Make object of your table
                    Owner obj=new Owner();
                    obj.OwnerID= userId;
                    obj.YouOtherColumns=valuetoinsert;
                    db.Owners.Add(obj);
                    db.SaveChanges();
                }

You can also refer this article for complete insert, update delete operations using entityframework:

http://www.codingfusion.com/Post/Repeater-Edit-Update-Delete-using-entity-framework

Thank you, but I’m getting and error:

"Cannot convert string to GUID, are you missing a cast?

The Membership services uses a Guid datatype. for the userId. The
string
userId  is a string. I tried to convert it, but it is still giving me errors:

//I tried to convert it without luck
System.Guid myId = new Guid.Parse(userId);
obj.OwnerID= myId;

I also tried to make the userId a guid instead of a string, :

Guid userId = mu.ProviderUserKey;

But, then I get the error:

"Cannot convert System.Guid to obj ProviderUserKey" And if I leave the ToString on the ProviderUserKey:

Guid userId =  mu.ProviderUserKey.ToString();

I get another error saying that Cannot convert System.Guid to string

anuj_koundal,

I tried this, I got the Guid issue resolved, but, I am using DynamicDataEntities. I have a new instance of The Owners model already instantiated.I need to add the item property as the filed for my values(firstName,lastName, etc…) How do I accss them? I
got this so far…

public void addUserInfoForm_InsertItem()
        {
            var item = new PoochiesPrix_4.Models.Owner();
            TryUpdateModel(item);
            if (ModelState.IsValid)
            {
                var userId = Membership.GetUser().ProviderUserKey.ToString();
                Guid myId = new Guid(userId);

                using (PoochiesPrixContext db = new PoochiesPrixContext())
                {
                    //==== Make object of your table
                    Owner obj = new Owner();
                    obj.OwnerID = myId;
                    obj.firstName = item; //how do I get the firsname value? I am using DynamicDataEntities and it is the item property
                    db.Owners.Add(obj);
                    db.SaveChanges();
                }
//The DynamicDataEntity Template looks like this:
<div class ="container">
        <asp:FormView ID="addUserInfoForm" runat="server" ItemType="PoochiesPrix_4.Models.Owner"
        InsertMethod="addUserInfoForm_InsertItem" DefaultMode="Insert"
        RenderOuterTable="false" OnItemInserted="addUserInfoForm_ItemInserted">
        <InsertItemTemplate>
        <fieldset>
            <ol>
                <asp:DynamicEntity ID="DynamicEntity2" runat="server" Mode="Insert" />

            </ol>
            <asp:Button ID="btnSave" runat="server" Text="Save" CommandName="Insert" />
            <asp:Button ID="btnCancel" runat="server" Text="Cancel" CausesValidation="false" OnClick="cancelButton_Click" />
        </fieldset>
    </InsertItemTemplate>
        </asp:FormView>
    </div><!--end of container-->

Its why I was doing this:

public void addUserInfoForm_InsertItem()
        {
            var item = new PoochiesPrix_4.Models.Owner();
            TryUpdateModel(item);
            if (ModelState.IsValid)
            {

Hi Mark_F,

If the FirstName was entered in FormView, you can try to use the following code:

using (PoochiesPrixContext db = new PoochiesPrixContext())
                {
                    //==== Make object of your table
                    Owner obj = new Owner();
                    obj.OwnerID = myId;
                    obj.firstName = item.firstName; //how do I get the firsname value? I am using DynamicDataEntities and it is the item property
                    db.Owners.Add(obj);
                    db.SaveChanges();
                }

Hope it helps.

Best Regards,
Terry Guo

using (PoochiesPrixContext db = new PoochiesPrixContext())
                {
                    //==== Make object of your table
                    Owner obj = new Owner();
                    obj.OwnerID = myId;
                    obj.firstName = item.firstName;
                    obj.lastName  = item.lastName;
                    
                    //and so forth for all of my FormView fields.
                    
                    db.Owners.Add(obj);
                    db.SaveChanges();
                }

Thank you both for the direction. I wasnt too far off. :-) Cheers!
Terry, yes. Thank you. I was able to go about it this way.

[RESOLVED]Error field template folder does not exist!the field template folder ' / dynamic data / field templates /' does not exist

Hello, i recieve this error; 

the field template folder ' / dynamic data / field templates /' does not exist

when i try to run this code;

<asp:FormView ID="FormView1" runat="server" ItemType="WebApplication6.Blog" 
        InsertMethod="insertItem" DefaultMode="Insert" 
        RenderOuterTable="false">
        <InsertItemTemplate>
            <fieldset>
                <ol>
                    <asp:DynamicEntity runat="server" Mode="Insert" />
                </ol>
                <asp:Button CommandName="Insert" Text="Lägg till" runat="server" />
            </fieldset>
        </InsertItemTemplate>
    </asp:FormView>

How do I solve that?

[RESOLVED]Using Datepicker with FormView

Hi All,

I have a Web forms application using EF Code First. I am using ModelBinding, and all is going well. I decided to try my hand at DynamicDataEntities which I installed from NuGet packageManager. I have a FormView that is bound to my entity data model, and
Im using the DynamicDataTemplates. I was just letting ASP build my form for me with the input fields, which worked fine, but, I need more control over the date fields. I want to add a jQuery Datepicker on the Date fields but I am having trouble.  I was using
this:

 <%--I was using a DynamicDataEntiy to render my form from my Model--%>

<asp:FormView ID="addDogForm" runat="server" ItemType="PoochiesPrix_4.Models.DogInfo"
        InsertMethod="addDogForm_InsertItem" DefaultMode="Insert"
        RenderOuterTable="false" OnItemInserted="addDogForm_ItemInserted">
        <InsertItemTemplate>
        <fieldset>
            <ol>
                <%--<asp:DynamicEntity ID="DynamicEntity1" runat="server" Mode="Insert" />--%>
           </ol>
            <asp:Button ID="btnSave" runat="server" Text="Save" CommandName="Insert" />
            <asp:Button ID="btnCancel" runat="server" Text="Cancel" CausesValidation="false" OnClick="cancelButton_Click" />
        </fieldset>
    </InsertItemTemplate>
    </asp:FormView>

This worked fine, but, In my Model:

//I have date fields that I want to show a Datepicker for

public class DogInfo
    {
        [Key, Display(Name = "DogInfoID")]
        [ScaffoldColumn(false)]
        public int DogInfoID { get; set; }

        [Required(ErrorMessage = "Name is required"), StringLength(35), Display(Name = "Dogs Name")]
        public string name { get; set; }

        [Required(ErrorMessage = "License number is required"), StringLength(15), Display(Name = "License Number")]
        public string licenseNumber { get; set; }

        [Required(ErrorMessage = "A date is required"), Display(Name = "Date License was Renewed")]
        [Range(typeof(DateTime), "1/1/2014", "1/1/3000", ErrorMessage = "Please provide a renewal date after 1/1/2014")]
        [DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = "{0:d}")]
        public DateTime dateLicenseRenewed { get; set; }

        [Required(ErrorMessage = "A date is required"), Display(Name = "Date License Expires")]
        [Range(typeof(DateTime), "1/1/2014", "1/1/3000", ErrorMessage = "Please provide a date after 1/1/2014")]
        [DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = "{0:d}")]
        public DateTime dateLicenseExpires { get; set; }

        [Display(Name = "Coat Color")]
        public string coatColor { get; set; }

        [Display(Name = "Eye Color")]
        public string eyeColor { get; set; }

        [Required(ErrorMessage = "Enter Male or Female"), StringLength(6, MinimumLength = 4), Display(Name = "Sex")]
        public string sex { get; set; }

        [Display(Name = "Breed")]
        public string breed { get; set; }

        [Required(ErrorMessage = "Required. If you do not know your dogs DOB, enter an approximate date."), Display(Name = "Birth Date")]
        public DateTime birthDate { get; set; }

        [Display(Name = "Microchip Number")]
        public string microchipNumber { get; set; }

        [Display(Name = "Breed Registration")]
        public string breedRegistration { get; set; }

        [Display(Name = "Breed Shelter Name")]
        public string breedShelterName { get; set; }

        [Display(Name = "Date Acquired")]
        [Range(typeof(DateTime), "1/1/1900", "1/1/3000", ErrorMessage = "Please an approximate date after 1/1/1900")]
        [DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = "{0:d}")]
        public Nullable<DateTime> dateAcquired { get; set; }

        [ScaffoldColumn(false)]
        public Guid OwnerID { get; set; }

        [EnumDataType(typeof(DogType)), Display(Name = "Dog Type")]
        public DogType dogType{ get; set; }


        [ScaffoldColumn(false)]
        public ICollection<DogPic> DogPics { get; set; }

        [ScaffoldColumn(false)]
        public List<Veternarian> Veternarians { get; set; }
    }
    public enum DogType
    {
        Adult,
        Puppy
    }

I have tried explicitedly adding the entities to the page in its each DynamicControl like this:

HTML:

<asp:FormView ID="addDogForm" runat="server" ItemType="PoochiesPrix_4.Models.DogInfo"
        InsertMethod="addDogForm_InsertItem" DefaultMode="Insert"
        RenderOuterTable="false" OnItemInserted="addDogForm_ItemInserted">
        <InsertItemTemplate>
        <fieldset>
            <ol>
                <%--<asp:DynamicEntity ID="DynamicEntity1" runat="server" Mode="Insert" />--%>
                <asp:DynamicControl ID="DynamicControl1" runat="server" DataField="name" Mode="Insert" />
                <asp:DynamicControl ID="DynamicControl2" runat="server" DataField="licenseNumber" Mode="Insert" />
                <asp:DynamicControl ID="DynamicControl3" runat="server" DataField="dateLicenseRenewed" Mode="Insert" />
                <asp:DynamicControl ID="DynamicControl4" runat="server" DataField="dateLicenseExpires" Mode="Insert" />
                <asp:DynamicControl ID="DynamicControl5" runat="server" DataField="coatColor" Mode="Insert" />
                <asp:DynamicControl ID="DynamicControl6" runat="server" DataField="eyeColor" Mode="Insert" />
                <asp:DynamicControl ID="DynamicControl7" runat="server" DataField="sex" Mode="Insert" />
                <asp:DynamicControl ID="DynamicControl8" runat="server" DataField="breed" Mode="Insert" />
                <asp:DynamicControl ID="DynamicControl9" runat="server" DataField="birthDate" Mode="Insert" />
                <asp:DynamicControl ID="DynamicControl10" runat="server" DataField="microchipNumber" Mode="Insert" />
                <asp:DynamicControl ID="DynamicControl11" runat="server" DataField="breedRegistration" Mode="Insert" />
                <asp:DynamicControl ID="DynamicControl12" runat="server" DataField="breedShelterName" Mode="Insert" />
                <asp:DynamicControl ID="DynamicControl13" runat="server" DataField="dateAcquired" Mode="Insert" />
                 <asp:DynamicControl ID="DynamicControl14" runat="server" DataField="dogType" Mode="Insert" />

            </ol>
            <asp:Button ID="btnSave" runat="server" Text="Save" CommandName="Insert" />
            <asp:Button ID="btnCancel" runat="server" Text="Cancel" CausesValidation="false" OnClick="cancelButton_Click" />
        </fieldset>
    </InsertItemTemplate>
    </asp:FormView>

Then editing the DateTime_Edit.ascx, Dynamic Template mark up:

<%-- Use the Juice Datepicker--%>

<juice:Datepicker runat="server" id="t1" targetcontrolid="DynamicControl3" />
<asp:TextBox ID="TextBox1" runat="server" CssClass="DDTextBox" Text='<%# FieldValueEditString %>' Columns="20"></asp:TextBox

Then in my DateTime_Edit.ascx.cs, I set a date range for my Calender:

protected void Page_Load(object sender, EventArgs e)
        {
            TextBox1.ToolTip = Column.Description;

            SetUpValidator(RequiredFieldValidator1);
            SetUpValidator(RegularExpressionValidator1);
            SetUpValidator(DynamicValidator1);
            SetUpCustomValidator(DateValidator);

        //when my calendar displays, restrict the date range the user can pick.

            RangeAttribute ra = (RangeAttribute)Column.Attributes[typeof(RangeAttribute)];
            if (ra != null)
            {
                t1.MinDate = ra.Minimum.ToString();
                t1.MaxDate = ra.Maximum.ToString();

            }
                
        }

I am getting an error that the value is null in my calendar. I know why this is happening, because I am using EF Code first, and I am dropping and recreating my Database evertime I run my application if my Model changes. I am not sure how to set a default
value in my code behind for this Calendar so that i do not get an error. I would like to set the current date as the date that displays. I believe that this will eliminate the null error too. I’m not sure though, since EF is using my database to build the
form. i hope that I explained this clear enough. Iwould like some direction on how to go about setting default values on my DynamidDataTemplate fileds.

Hi,

If you want to set default date for the jQuery Datepicker, you could try:

$( ".selector" ).datepicker( "setDate", new Date());
// Or on the init
$( ".selector" ).datepicker({ defaultDate: new Date() });

For more information, you could refer to:

http://stackoverflow.com/questions/14580749/jquery-datepicker-set-default-date

http://stackoverflow.com/questions/4915990/set-todays-date-as-default-date-in-jquery-ui-datepicker

Regards

Shawn,

Thanks allot for the info.It helped allot. I have all of my DatePickers working now.I found that I just needed to set each Datepicker for TexBox1 in the DynamicDataEntity Template, DateTime_Edit.ascx:

<juice:Datepicker runat="server" id="t1" targetcontrolid="TextBox1" />
<juice:Datepicker runat="server" id="t2" targetcontrolid="TextBox1" />
<juice:Datepicker runat="server" id="t3" targetcontrolid="TextBox1" />
<juice:Datepicker runat="server" id="t4" targetcontrolid="TextBox1" />
<asp:TextBox ID="TextBox1" runat="server" CssClass="DDTextBox" Text='<%# FieldValueEditString %>' Columns="20"></asp:TextBox>

Then in the DateTime_Edit.cs file, i did this:

RangeAttribute ra = (RangeAttribute)Column.Attributes[typeof(RangeAttribute)];
            if (ra != null)
            {
                t1.MinDate = ra.Minimum.ToString();
                t1.MaxDate = ra.Maximum.ToString();
                t2.MinDate = ra.Minimum.ToString();
                t2.MaxDate = ra.Maximum.ToString();
                t4.MinDate = ra.Minimum.ToString();
                t4.MaxDate = ra.Maximum.ToString();

            }

In my Page, I put a script:

<script type="text/javascript">
        $(function () {
            $('#t1').datepicker();
            $('#t1').datepicker('setDate', new Date());
        });
    </script>

For each one that I wanted a default date set in. Actually, when I set the targetcontrolid to "TextBox1, the page ran fine." Thanks for the links though. They are good. Cheers!