Category Archives: FormView

FormView

MVC and ASP.Net website in one solution

Hi

I wanted to know how to reference my ASP.Net aspx page in my MVC project.

I know how to do it with Areas and a seperate MVC Project. BUT when I add an ASP.Net Application I’m unsure how to route to the Default.aspx page.

I followed:

http://dotnetslackers.com/articles/aspnet/Storing-ASP-NET-MVC-Controllers-Views-in-separate-assemblies.aspx

The core and setup pages relate to the MVC but how do I reference my Default.aspx page. I get a 404 when I type in localhost/Default.aspx

I did add the default aspx page to the bin folder of the mvc. But not sure if I should do a Core folder and Setup as in article for the ASP.Net application as it doesn’t work with Controllers and Views?

Core folder ViewEngine:

public class CMSViewEngine : WebFormViewEngine
{
    public CMSViewEngine()
    {
        MasterLocationFormats = new string[]
        {
            "~/bin/Views/{1}/{0}.master",  
            "~/bin/Views/Shared/{0}.master"
        };
        ViewLocationFormats = new string[]
        {
            "~/bin/Views/{1}/{0}.aspx",  
            "~/bin/Views/{1}/{0}.ascx",  
            "~/bin/Views/Shared/{0}.aspx",  
            "~/bin/Views/Shared/{0}.ascx"
        };
    }
}

Setup:

public class CMSSetup
{
    public static void Setup()
    {
        SetupControllers();
        SetupViewEngine();
    }
    private static void SetupViewEngine()
    {
        ViewEngines.Engines.Add(new CMSViewEngine());
    }
    private static void SetupControllers()
    {
        ControllerBuilder.Current.DefaultNamespaces.Add("CMS.Controllers");
    }
    public static void SetupRoutes(RouteCollection routes)
    {
    }
}

Global asax:

public static void RegisterRoutes(RouteCollection routes)
        {
            routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
            routes.IgnoreRoute("{resource}.aspx/{*pathInfo}");

            routes.MapRoute(
                "Default", // Route name
                "{controller}/{action}/{id}", // URL with parameters
                new { controller = "Home", action = "Index", id = UrlParameter.Optional }, new[]{"HCCWebTemplate.Controllers"}
            );

        }

        /// <summary>
        /// Application Start where areas are registered
        /// </summary>
        protected void Application_Start()
        {
            CMSSetup.Setup();


            AreaRegistration.RegisterAllAreas();

            RegisterRoutes(RouteTable.Routes);
        }

They reason why is that my MVC is a framework that will be used by other developers and some of them only need to develop Single Page Applications. So only one web page to slot into my framework and they are more comfortable with ASP.Net Application Web Pages.

Hope someone can help me.

Thanks

 

Hi sunettew1,

What’s the version of your MVC project?

For that link that you provide, it uses the MVC 2. In the MVC 2 project, it uses
aspx files as views.

For the higher version of MVC project, it uses cshtml files as views, to enable web forms in the asp.net mvc project, you just need to add this code below to ignore the web forms request.

routes.IgnoreRoute("{resource}.aspx/{*pathInfo}");

The files in the view folder, we can’t access it directly.

Best Regards

Starain Chen

Hi

I use MVC 2. How do I reference the website’s pages because there is no controller?

Thanks

Hi sunettew1,

You could try to use MapPageRoute method or access it directly.

# RouteCollection.MapPageRoute Method

http://msdn.microsoft.com/en-us/library/system.web.routing.routecollection.mappageroute(v=vs.100).aspx

Best Regards

Starain

[RESOLVED]how to get the selected checkbox values from view to controller through model data

public class checkbox

{

int id;

string name;

bool selected;

}

and I call this in viewmodel as List<checkbox> list

when I am binding the list into view is successfully but when I am getting the selected values the model data shows list: count=0 when selected otherwise shows null

@foreact(var item in model.list){

<input type="checkbox" @selected name="list" value="@item.id">

}

how can I get these values from view to controller

this is not good 

Siva_540

name="list"

Please read http://haacked.com/archive/2008/10/23/model-binding-to-a-list.aspx/

Hi Siva,

assign a name to your checkbox:

<input name="gender" type="checkbox" id="@checkBoxId" class="chkclass" value="@names.Value" />

Then in your action do something like below:

[HttpPost]
        public ActionResult HandleFormSubmit(string[] gender,
             MembershipFormViewModel model)
        {
            //model not valid, do not save, but return current umbraco page
            if (ModelState.IsValid == false)
            {
                return CurrentUmbracoPage();
            }
            string test = "Gender: " + model.Gender + Environment.NewLine; //getting null here
            return RedirectToCurrentUmbracoPage();
        }

 

you need to understand how checkboxes post their data. if they have a name attribute, when checked, they post name=value, else if not checked its value is not included in the postback data. so if you had three checkboxes

   <input type="checkbox" name="list" value="1" checked>
   <input type="checkbox" name="list" value="2" >
   <input type="checkbox" name="list" value="3" checked>

and the user did not change the check, the postback data would include:

   list=1&list=2

the mvc binder can bind this data to a string array or numeric array. but that is not what you have. if you change the checkboxes to:

  <input type="checkbox" name="list.id" value="1" checked>
   <input type="checkbox" name="list.id" value="2" >
   <input type="checkbox" name="list.id" value="3" checked>

the binder could blind it your list, but it would only contain 2 entries, and only the id would be filled in. to get you complete list posted back it would be:

 

@for(var i=0; i < model.list.Count; ++i){
   @Html.HiddenFor(m=>m.list[i].id)
   @Html.HiddenFor(m=>m.list[i].name)
   @Html.CheckboxFor(m=>m.list[i].selected)
}


if you wanted to manually handle the  checkbox its:

    <input type="checkbox" @(Model.list[i].selected ? "checked" : "") name="list[@(i)]" value="true">

[RESOLVED]How to pseudo click Update link button from javascript

Hi,

How can I click a Formview Update link button from javascript ?

Hi shtrudel,

From your description, if you want to add client event for update button, you could refer to the following code.

    <script type="text/javascript">
        function updateClick() {
            alert("Update?");
            return false;
            
        }
    </script>

        <asp:FormView ID="FormView1" runat="server" DataKeyNames="Id" DataSourceID="SqlDataSource1" OnItemUpdating="FormView1_ItemUpdating" DefaultMode="Edit">
            <EditItemTemplate>
                Id:
                <asp:Label ID="IdLabel1" runat="server" Text='<%# Eval("Id") %>' />
                <br />
                Name :
                <asp:TextBox ID="NameTextBox" runat="server" Text='<%# Bind("Name") %>' />
                <br />
                Gender :
                <asp:TextBox ID="GenderTextBox" runat="server" Text='<%# Bind("Gender") %>' />
                <br />
                <asp:LinkButton ID="UpdateButton" runat="server" CausesValidation="True" OnClientClick="return updateClick();" CommandName="Update" Text="Update" />
                &nbsp;<asp:LinkButton ID="UpdateCancelButton" runat="server" CausesValidation="False" CommandName="Cancel" Text="Cancel" />
            </EditItemTemplate>
            ...

        </asp:FormView>

If you want to trigger update button click event from JavaScript. You could refer to the following code.

document.getElementById('<%= FormView1.FindControl("UpdateButton").ClientID %>').click()

If you have any other questions about my reply, please let me know freely.

Best Regards,
Dillion

[RESOLVED]How to Make a Javascript Function Run ONLY if a Control is Enabled

ASP.Net 4.5.  IIS 7.  Visual Studio 2012.  JavaScript.

I have placed a JavaScript function at the top of my asp.net (aspx) page.  It runs when the page is opened (and produces an error because the EnterForm (formview) control it references is not enabled).  How can I make this function run its code ONLY if the
control is enabled?  Here is the code:

        function calcTotalHours() {
                var TotalHours = document.getElementById('<%= EnterForm.Findcontrol("TotalFacHoursTextBox").ClientId %>');
                var Hours = ['<%= EnterForm.Findcontrol("SundayHoursTextBox").ClientId %>', '<%= EnterForm.Findcontrol("MondayHoursTextBox").ClientId %>', '<%= EnterForm.Findcontrol("TuesdayHoursTextBox").ClientId %>', '<%= EnterForm.Findcontrol("WednesdayHoursTextBox").ClientId %>', '<%= EnterForm.Findcontrol("ThursdayHoursTextBox").ClientId %>', '<%= EnterForm.Findcontrol("FridayHoursTextBox").ClientId %>', '<%= EnterForm.Findcontrol("SaturdayHoursTextBox").ClientId %>'];
                var total = 0;
                for (var i = 0; i <= 6; i++) {
                    if (!isNaN(document.getElementById(Hours[i]).value) && document.getElementById(Hours[i]).value != "") {
                        total += eval(document.getElementById(Hours[i]).value);
                    }
                }
                TotalHours.value = total;
        }

Hi Chaplain,

Thanks for your post.

Firstly, I’d like to know when do you call calcTotalHours() function?

Chaplain Doug

It runs when the page is opened (and produces an error because the EnterForm (formview) control it references is not enabled). 

Secondly, what is the error you got? It will help us understand your problem.

Thirdly, we could check the value of “TotalHours” and “Hours” when the EnterForm (formview) control is not enabled. May be the value is null (or undefined), then we could modify the code to determine whether the EnterForm is enabled or not, and make javascript
function run only if the EnterForm is enabled.

The code may look like as below.

function calcTotalHours() {
    var TotalHours = document.getElementById('<%= EnterForm.Findcontrol("TotalFacHoursTextBox").ClientId %>');
    var Hours = ['<%= EnterForm.Findcontrol("SundayHoursTextBox").ClientId %>', '<%= EnterForm.Findcontrol("MondayHoursTextBox").ClientId %>', '<%= EnterForm.Findcontrol("TuesdayHoursTextBox").ClientId %>', '<%= EnterForm.Findcontrol("WednesdayHoursTextBox").ClientId %>', '<%= EnterForm.Findcontrol("ThursdayHoursTextBox").ClientId %>', '<%= EnterForm.Findcontrol("FridayHoursTextBox").ClientId %>', '<%= EnterForm.Findcontrol("SaturdayHoursTextBox").ClientId %>'];

    if (TotalHours == "null" || Hours == "null") {
        return false;
    }

    var total = 0;
    for (var i = 0; i <= 6; i++) {
        if (!isNaN(document.getElementById(Hours[i]).value) && document.getElementById(Hours[i]).value != "") {
            total += eval(document.getElementById(Hours[i]).value);
        }
    }
    TotalHours.value = total;
} 

Hope it will be helpful to you.

Best Regards,

Fei Han

How can I manipulate (clear file, set background color) the AsyncFileUpload control with jQuery?

I have just started to learn (and use) jQuery this week, so I have no experience.

I am calling the js function from the UploadedComplete event if it is determined that the file type is not allowed.

C#

protected void AsyncFileUpload_FormView_DOC_UploadedComplete(object sender, AsyncFileUploadEventArgs e)
{
    ExitStatus exitStatus = IsExtensionAllowed((AsyncFileUpload)sender, FileType.word);
    if (!exitStatus.Success)
    {
        ScriptManager.RegisterStartupScript(this, this.GetType(), "", "ClearAsyncFileUpload('" + ((AsyncFileUpload)sender).ClientID + "');", true);
    }
}

HTML

<script type="text/javascript">
function ClearAsyncFileUpload(senderClientID) { var myID = "#" + senderClientID + "_ctl02"; $(myID).val(''); $(myID).css('background-color', 'red'); }
</script>

the statement var myID = "#" + senderClientID + "_ctl02"; 

does produce the following: "#ctl00_ContentPlaceHolder_BODY_FormView_Specification_AsyncFileUpload_FormView_DOC_ctl02"

but nothing happens when $(myID).val(”); and .css is reached.

The HTML ID of the AsyncFileUpload is AsyncFileUpload_FormView_DOC.

The ClientID sent from the server to the js function is ctl00_ContentPlaceHolder_BODY_FormView_Specification_AsyncFileUpload_FormView_DOC 

When I run the following $(‘#ctl00_ContentPlaceHolder_BODY_FormView_Specification_AsyncFileUpload_FormView_DOC’); in the Chrome console I get the following:

<div id="ctl00_ContentPlaceHolder_BODY_FormView_Specification_AsyncFileUpload_FormView_DOC" style="color:White;">
	<input type="hidden" name="ctl00$ContentPlaceHolder_BODY$FormView_Specification$AsyncFileUpload_FormView_DOC$ctl00" 
		id="ctl00_ContentPlaceHolder_BODY_FormView_Specification_AsyncFileUpload_FormView_DOC_ctl00" 
		value="C:fakepathsome_file.txt">
		
	<div id="ctl00_ContentPlaceHolder_BODY_FormView_Specification_AsyncFileUpload_FormView_DOC_ctl01">
		<input name="ctl00$ContentPlaceHolder_BODY$FormView_Specification$AsyncFileUpload_FormView_DOC$ctl02" type="file" 
			id="ctl00_ContentPlaceHolder_BODY_FormView_Specification_AsyncFileUpload_FormView_DOC_ctl02" style="width: 
			250px; background-color: green;">
	</div>
</div>

It appears that _ctl02 is consistent (at least in the two AsyncFileUpload controls i examined).

When the control is rendered it appear to create two (2) inputs, one type="file" and one type="hidden" 

When I run the following in the Chrome console. I get the desired effect (IE of course, is another story).

$('#ctl00_ContentPlaceHolder_BODY_FormView_Specification_AsyncFileUpload_FormView_DOC_ctl02').val('');
$('#ctl00_ContentPlaceHolder_BODY_FormView_Specification_AsyncFileUpload_FormView_DOC_ctl02').css('background-color', 'red');

When I to do it from the js function however, nothing happens.

Thanks for any suggestions.

Hi matt.gulick

For your issues is related with CMS.MediaLibrary  which is out of  our  support scope ,please post your issue to the link below for a  professional solution.

http://www.kentico.com/Product/All-Features/Content-Management/Media-Library

According to your post , you want to upload a file , If I don’t misunderstand you. Please try my code as below.

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="WebForm2.aspx.cs" Inherits="WebApplicationFor2.WebForm2" %>
<%@ Register Assembly="AjaxControlToolkit" Namespace="AjaxControlToolkit" TagPrefix="ajaxToolkit" %> 
<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>      
<script type="text/javascript">
    function showConfirmation() {
        document.getElementById('Label1').innerText = 'file upload complete.';
    }
</script> 
</head>
<body>
    <form id="form1" runat="server">
        <div>
            <ajaxToolkit:ToolkitScriptManager ID="ToolkitScriptManager1" runat="server"></ajaxToolkit:ToolkitScriptManager>
        <ajaxToolkit:AsyncFileUpload ID="AsyncFileUpload1" runat="server"  
            OnUploadedComplete="AsyncFileUpload1_UploadComplete"  
            OnClientUploadComplete="showConfirmation"  
            BackColor="green"/>
        <asp:Label ID="Label1" runat="server" Font-Size="Large" Font-Bold="True" ForeColor="red" Font-Names="Comic Sans MS"></asp:Label>
	</div>
    </form>
</body>
</html>

protected void AsyncFileUpload1_UploadComplete(object sender, AjaxControlToolkit.AsyncFileUploadEventArgs e)  
        {
            string strfilename = System.IO.Path.GetFileName(AsyncFileUpload1.PostedFile.FileName);
            string filePath = @"D:Doc" + strfilename; //revise your path according to your demands
            AsyncFileUpload1.SaveAs(filePath);  
        }  

 

Hope this can help you .

Best regards,

Aswecan

Aswecan

Hi matt.gulick

For your issues is related with CMS.MediaLibrary  which is out of  our  support scope ,please post your issue to the link below for a  professional solution.

Thanks for taking the time to reply, but nothing in your reply relates at all to my issue other then the event to which I was using to trigger my jQuery call.

I don’t know what I wrote that would make you think my issue pertains to this CMS.MediaLibrary, but it has nothing to do with it (I don’t even know what that is).

I know how to upload a file, I was not asking that. I was trying to change some properties of the AsyncFileUpload control triggered from the UploadComplete event.

I am not uploading the file on UploadComplete, I am just doing my own file validation, and if I determine that the file selected is invalid I wanted to clear the file name from the control and change the background to red.

Hi matt.gulick,

I have tried your code in my computer. and I  find that when  I click the upload button, I find that the javascript function not fire in the client side.

I suggest that you can set a  breakpoint on your  "ClearAsyncFileUpload" function to check if it can be hit .

Second, I am not quite sure ,since the file is not valid, why you still upload it to the server ,then clear the file name and change background color.

Best Regards,

Kevin Shen.

The javascript function "ClearAsyncFileUpload" is being triggered from the server side AsyncFileUpload_UploadComplete event. I have set break points in the server and client side as well as placing an alert box in the javascript (which
did appear).

Perhaps your visual studio is not configered to handle client-side debugging. I had to change a few settings in IE in order for it to be able to step through.

As for the file uploading, I am not uploading the file if it is invalid.

In my server side i code i call a method that determines the file validity and returns a bool and string (exit status and exit message).

The UploadComplete event examines the existStatus (bool) and asks, if NOT success (true), then call the javascript function to clear the AsyncFileUpload control and turn background red, so as to inform the user that the file they selected is invalid. I already
advise them via text that the field requires a pdf document, and i also pop up a modal if they select a file other than pdf. Clearing the AsyncFileUpload control is just another step in preventing the user from attempting to save the record.

In the save function, I validate the file again.

  1. On AsyncFileUpload_UploadComplete, files validity is determined. If invalid, alert box informs user of invalid file selection ….. and I want to clear the file from the AsyncFileUpload control and set background to red, like it would be if file failed
    to load into control.
  2. If user ignores alert and attempts to save the record, then another file validation is run and if invalid, file save will not occur.

If i could clear the file control in step 1 then i would not have to validate the file again in step 2.

[RESOLVED]Show Formview in jQuery dialog

Hi there,

I have a page in which I have Gridview control and a Formview control, the Formview initial state is Insert, when the user Select a row from the gridview I change the Formview mode to Edit and let the user edit the row. everything work fine, as expected. 

I want to display the formview in a jQuery dialog and show that dialog to the user when she click the gridview Select link,

how can I achieve that ?

regards,

Thanks Lokesh,

It does show how to display row data in jquery dialog,

what I am looking for is how to use Formview (Inser/Edit mode) from within a jQuery dialog.

you can use ModalPopUpExtender to show the formview.

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

Can you post your code , so that i can understand better !!! 

Its a common scenario for Gridview showing rows and a Formview for editing/inserting records,

What I want is to show the Formview from within a jQuery dialog.

Hi shtrudel,

Thanks for your post.

shtrudel

What I want is to show the Formview from within a jQuery dialog.

As for your problem, you could refer to the following similar issues.

Hope it will be helpful to you.

Best Regards,

Fei Han

Displaying message while postback

Hi,

How can I display a message to the user while data control (e.g. Grigview, Formview) is populating from server ?

Thanks,

You’ll need to populate your gridview using ajax, updatepanel etc so the work can happen after the actual page has loaded, this lets you show a message until the ajax work has finished.  Or you can show a "please wait" page that redirects to your actual
page so the browser shows the waiting page until the actual page has returned from the server.

Hi shtrudel,

Thanks for your post.

The UpdateProgress control could provide status information about partial-page updates in UpdatePanel controls, and you can customize the default content and the layout of the UpdateProgress control. So you could use UpdateProgress control  to show that
an asynchronus method is working.

For more information about UpdateProgress Control, you could refer to the following link.

Besides, you could refer to this sample.

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
    <style type="text/css">
        #UpdatePanel1, #UpdateProgress1 {
            border-right: gray 1px solid;
            border-top: gray 1px solid;
            border-left: gray 1px solid;
            border-bottom: gray 1px solid;
        }

        #UpdatePanel1 {
            width: 200px;
            height: 200px;
            position: relative;
            float: left;
            margin-left: 10px;
            margin-top: 10px;
        }

        #UpdateProgress1 {
            width: 400px;
            background-color: #FFC080;
            bottom: 0%;
            left: 0px;
            position: absolute;
        }
    </style>


    <script runat="server">
        protected void Button_Click(object sender, EventArgs e)
        {
            System.Threading.Thread.Sleep(3000);
        }
    </script>

</head>
<body>
    <form id="form1" runat="server">
        <asp:ScriptManager ID="ScriptManager1" runat="server"></asp:ScriptManager>
        <div>
            <asp:UpdatePanel ID="UpdatePanel1" UpdateMode="Conditional" runat="server">
                <ContentTemplate>
                    <%=DateTime.Now.ToString() %>
                    <br />
                    <asp:Button ID="Button1" runat="server" Text="Refresh Panel" OnClick="Button_Click" />
                </ContentTemplate>
            </asp:UpdatePanel>

            <asp:UpdateProgress ID="UpdateProgress1" runat="server">
                <ProgressTemplate>
                    Update in progress...
                </ProgressTemplate>
            </asp:UpdateProgress>

        </div>
    </form>
</body>
</html>

Hope it will be helpful to you.

Best Regards,

Fei Han

Thank you for your answers,

I prefer not to use the ajax controls… maybe because I do not really understand what’s behind the scene’s

shtrudel

I prefer not to use the ajax controls

You are going to have to use some kind of AJAX-enabled approach to do what you want. If you prefer not to use the AJAX controls, you can use jQuery. 

Script Throws Error After a Formview Cancel Command

I have JavaScript on my aspx page for a function that references controls on a formview.  This function works fine until the page/formview tries to reload after I click the "Cancel" button on the formview.  When the page tries to reload, I get an "Object
reference not set to an instance of an object" error on the line in bold below (var TotalHours = . . .).  First, why would I get this error?  This code does not actually run after the Cancel (the alert does not come up), but for some reason the debugger throws
the error and stops the code.  Any help would be greatly appreciated!

                    <script type="text/jscript">
                        function calcTotalHours2() {
                            var LastCommand = '<%= Session("EditFormLastCommand")%>';
                            alert(LastCommand);
                            if (LastCommand != 'Cancel') {
                                var TotalHours = document.getElementById('<%= EditForm.FindControl("TotalFacHoursTextBox").ClientID%>');
                                var Hours = ['<%= EditForm.FindControl("SundayHoursTextBox").ClientID%>', '<%= EditForm.FindControl("MondayHoursTextBox").ClientID%>', '<%= EditForm.FindControl("TuesdayHoursTextBox").ClientID%>', '<%= EditForm.FindControl("WednesdayHoursTextBox").ClientID%>', '<%= EditForm.FindControl("ThursdayHoursTextBox").ClientID%>', '<%= EditForm.FindControl("FridayHoursTextBox").ClientID%>', '<%= EditForm.FindControl("SaturdayHoursTextBox").ClientID%>'];
                                var total = 0;
                                for (var i = 0; i <= 6; i++) {
                                    if (!isNaN(document.getElementById(Hours[i]).value) && document.getElementById(Hours[i]).value != "") {
                                        total += eval(document.getElementById(Hours[i]).value);
                                    }
                                }
                                TotalHours.value = total;
                            }
                        }
                    </script>

try with below code , i just added document.ready to make sure your function should call after page rendered

<script type="text/jscript">

 $(document).ready(function () {
         function calcTotalHours2() {
                            var LastCommand = '<%= Session("EditFormLastCommand")%>';
                            alert(LastCommand);
                            if (LastCommand != 'Cancel') {
                                var TotalHours = document.getElementById('<%= EditForm.FindControl("TotalFacHoursTextBox").ClientID%>');
                                var Hours = ['<%= EditForm.FindControl("SundayHoursTextBox").ClientID%>', '<%= EditForm.FindControl("MondayHoursTextBox").ClientID%>', '<%= EditForm.FindControl("TuesdayHoursTextBox").ClientID%>', '<%= EditForm.FindControl("WednesdayHoursTextBox").ClientID%>', '<%= EditForm.FindControl("ThursdayHoursTextBox").ClientID%>', '<%= EditForm.FindControl("FridayHoursTextBox").ClientID%>', '<%= EditForm.FindControl("SaturdayHoursTextBox").ClientID%>'];
                                var total = 0;
                                for (var i = 0; i <= 6; i++) {
                                    if (!isNaN(document.getElementById(Hours[i]).value) && document.getElementById(Hours[i]).value != "") {
                                        total += eval(document.getElementById(Hours[i]).value);
                                    }
                                }
                                TotalHours.value = total;
                            }
                        }
    });
</script>

 

The debugger throws an error on the "$(document).ready(function
() {" line saying,

Unhandled exception on line 524 column 25 (the first $ before (document))

0x800a138f – JavaScript routine error: Object expected

I think I have tried the $(document).ready before and gotten the same error.  Is this code valid for my aspx page?  Please help.  Thanks.

P.S.  I am scripting JavaScript NOT JQuery.  I read the the document ready is JQuery code????

This is a JQuery function.  How do I code my page so it can understand JQuery?  What do I have to include?

Okay, I figured out how to include JQuery on the page.  Now I do not get the error on $.  However, when the function calctotalhours2 is attempted to be called on a textbox OnChange client event, it gives an error that the function is undefined.

PLEASE LET ME RESTATE THE PROBLEM.

Why does my JavaScript code throw an error after I execute a Cancel command on a formview?  The code is not running after the Cancel, as it is only called by textbox OnChange events.  Yet when the page is reloaded after the Cancel, the first line in the
script below errors out with "Object reference not set to an instance of an object."  This script is embedded just before the </asp:Panel> tag for the panel in which the formview is contained.

                    <script type="text/javascript">
                        function calcTotalHours2() {
                            var TotalHours = document.getElementById('<%= EditForm.FindControl("TotalFacHoursTextBox").ClientID%>');
                            var Hours = ['<%= EditForm.FindControl("SundayHoursTextBox").ClientID%>', '<%= EditForm.FindControl("MondayHoursTextBox").ClientID%>', '<%= EditForm.FindControl("TuesdayHoursTextBox").ClientID%>', '<%= EditForm.FindControl("WednesdayHoursTextBox").ClientID%>', '<%= EditForm.FindControl("ThursdayHoursTextBox").ClientID%>', '<%= EditForm.FindControl("FridayHoursTextBox").ClientID%>', '<%= EditForm.FindControl("SaturdayHoursTextBox").ClientID%>'];
                            var total = 0;
                            for (var i = 0; i <= 6; i++) {
                                if (!isNaN(document.getElementById(Hours[i]).value) && document.getElementById(Hours[i]).value != "") {
                                    total += eval(document.getElementById(Hours[i]).value);
                                }
                            }
                            TotalHours.value = total;
                        }
                    </script>

 

I note that the problem is unique to a formview in edit/update mode.  I have the same functionality for an identical formview that is in insert mode.  The cancel works, the PreRender code has no problem finding the controls, and the javascript for its function
has no problem fidning the controls.  It is unique to the edit/update form.  Any ideas?

Hi Chaplain ,

As far as i know ,if your formview in edit mode,you can not find the control which is not in the edittemplate.

I suggest that if your control is not in the edititemtempate.

Best Regards,

Kevin Shen.

[RESOLVED]Formview Not Visible

Hello. I have a little problem. I cant see the controls on this page either in Design mode or when I run it. The code is below. Thank you.

<asp:Repeater ID="Repeater1" runat="server">

                    <ItemTemplate>
                    
                    <asp:FormView ID="FormView1" runat="server">
                    
                    <ItemTemplate>
                    
                    <!-- Products -->
		     <ul class="products">
			<li class="product first">
				<a href="category-products.html">
				<img src="images/placeholder/small-product-220x164.jpg" alt="" title="" />
				<h3>Condos For Sale</h3>
				</a>
			</li>
										
			li class="product">
			           <a href="category-products.html">
				<img src="images/placeholder/small-product-220x164.jpg" alt="" title="" />
				<h3>Appartments For Rent</h3>
				</a>
			</li>

                               <li class="product last">
			       <a href="category-products.html">
			       <img src="images/placeholder/small-product-220x164.jpg" alt="" title="" />
				<h3>Condos For Rent</h3>
				</a>
			</li>

                    </ul>
                    
                    </ItemTemplate>
                    
                    </asp:FormView>

                    </ItemTemplate>
                    
                    </asp:Repeater>

I think the ItemTemplate tag is malformed.  You have an additional ItemTemplate tag ‘inside’ that first one.

I think there should only be one ItemTemplate, and you have two there. Plust, the ‘open’ of the FormView is in one, and the rest of the Form is in the other.  Put all the FormView stuff into either one, and try that.

You only able to see the FormView if you bind to DataSource with any records exist. If no record, the FormView will invisible except in insert mode.

Repeater control repeats the data’s if the data exist on debug. You can’t see in design mode because repeater contains them, if you compile you can manage. And also if you want to manage the control’s at repeater. Try This ;

protected void Repeater1_ItemDataBound(object sender, RepeaterItemEventArgs e)
    {
        if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)
        {
        YourItem yourItemName = new YourItem();
        yourItemName= (yourItem)e.Item.FindControl("repeaterControlWhichYouWantToManage");

        string strName = repeaterControlWhichYouWantToManage.Text.ToString();
    }
    }

Thanks

[RESOLVED]How to get jQuery calendar date popup to work?

Does anyone know a way to get this
calendar time popup
to work inside of Formview control? I tested with a plan page and it works fine but not when it’s under a FormView control Here’s the error:

Error    7    The name ‘txInstDateTime’ does not exist in the current context    S:AlumniASPXAdminadminEditAlumniMassEmail.aspx

that’s b/c your textbox is inside another control, making it not readable

give your textbox a class, 

<asp:TextBox id="txInstDateTime" runat="server" class="someClass" />
$('.someClass').datetimepicker();

Thanks for the quick response.

Okay, so now, I got this error in FireFox’s Erro Console:

Error: $(".insDateTime").datetimepicker is not a function
Source File: http://c-123/mySite/adminEditAlumniMassEmail.aspx?emailID=999999999
Line: 43

It is referring to this line: AMPM: true

In this:

<link href="~/css/jquery-ui-1.8.18.custom.css" rel="stylesheet" type="text/css" />
    <script src="~/Scripts/jquery-1.7.1.min.js" type="text/javascript"></script>
    <script src="~/Scripts/jquery-ui-1.8.18.custom.min.js" type="text/javascript"></script>
    <script src="~/Scripts/jquery-ui-timepicker-addon.js" type="text/javascript"></script>
    <script src="~/Scripts/jquery-ui-sliderAccess.js" type="text/javascript"></script>
    <script language="javascript" type="text/javascript">
        $(document).ready(function () {
            //alert("got here");
            $('.insDateTime').datetimepicker({
                AMPM: true
            });
        });
    </script>

your script declaration seems like you have it in a masterpage. i believe you cannot use "~" as this is for server side only 

<script runat="server" type="text/javascript"
  src='<%= Page.ResolveUrl("~/jquery.js") %>'></script>

also, you should put your script code on the bottom of the page, rather than the top. the browser reads the page from top to bottom. it may be trying to access the control when it is not already rendered

Awsome! It works. It’s the ~/ that causes the problem. I removed it and use ../ and now it works just fine.