I have an existing .net application rendering data in razor, and I would like to display a specific node from an XML string for each record using razor. But I am not sure how to go about writing it. There will be 50+ records in the model, so I want to make sure it's efficient.

Each record in the model will have it's own xmldata. For example:


Model:

namespace Project.Web.ViewModels
{  
   public class SampleModel  
   {  
      public int id { get; set; }  
      public string xmldata { get; set; }  
   }  
}


xmldata for first record:

<content>
  <user>
    <firstname>Jim</firstname>
    <lastname>Smith</lastname>
  </user>
</content>


xmldata for second record:

<content>
  <user>
    <firstname>John</firstname>
    <lastname>Jones</lastname>
  </user>
</content>


csHtml:

@model Project.Web.ViewModels.SampleModel
@foreach (item in Model) {
   <p><b>ID:</b> @item.id</p>
   <p><b>FirstName:</b> //Add firstname from @item.xmldata here</p>
   <p><b>LastName:</b> //Add lastname from @item.xmldata here</p>
   <br>
}


Desired output:

ID: 1
FirstName: Jim
LastName: Smith

ID: 2
FirstName: John
LastName: Jones


An example of how to write the razor code in cshtml would be greatly appreciated!

I have a super quick question for you that I would imagine you could answer quickly. I have a subject allocation page on the web site that i'm building, I'm having 2 select option fields and I will choose some values and when I click a button "assign" it should be inserted into a table

Guys I am stuck with code please help. Thanks For the Help In Advance**

database connections with tables

Layout = "~/_SiteLayout.cshtml";
Page.Title = "SemI";
var db = Database.Open("TimeTableGen");
var selectCommand = "SELECT Facultyname FROM Faculty";
var selectCommand2 = "SELECT Subname FROM Sublist";
var selectedData = db.Query(selectCommand);
var selectedData2 = db.Query(selectCommand2);

<head>
    <meta charset="utf-8" />
    <title></title>
</head>
<body>

               <br>
   **subject table which rus 8 times as 6 subjects + 2labs in this we have been retreiving data from tables of faculty and semI tables  **             
  @for(int i=0;i<=7;i++) {  

<select name="Subject name">
@foreach(var row in selectedData2){
    foreach(var item in row.Subname.ToString().Split(new [] {','})){
    <option>@item</option>
    }
}

<select name="FacultyList">
@foreach(var row in selectedData){
    foreach(var item in row.Facultyname.ToString().Split(new [] {','})){
    <option>@item</option>
    }
}


THIS IS FOR LOOP TO CREATE 8 SUBJECTS

      THIS IS TO STORE THE VALUES FROM ABOVE SELECT OPTIONS TO STORE TO A NEW DB TABLE        
        if (IsPost)

          var db1 = Database.Open("TimeTableGen");
          var insertQuery = "INSERT INTO SemIsatb (Subname,Facultyname) " +
            "VALUES (@0, @1)";
          db.Execute(insertQuery, Subname, Facultyname);
         // Display the page that lists products.
         Response.Redirect("~/");


  <br><br>             
 <form action="~/" class="inline">
<button type="submit" value="Assign">Assign</button>

</body>

please tell me how to write code for "assign button" such that i am taking values from those select fields and to be inserted into a table

ViewData["ChildPageMetaConent"] = lstPageMetaContentChilds; // from this line i get data from database and set to ViewData .

Example : in ViewData["ChildPageMetaConent"] have list class. You can check in Image. enter image description here

And on Master.cshtml I am accessing ViewData["ChildPageMetaConent"] variable and gointo to write on page but its print on page like a text . enter image description here

And on HTMl its look like this : enter image description here

It seems like I have a little mistake in my code. But I cant find it.

So, I'm calling an Action in my Controller from my ajax function.

var serviceURL = '/Vm/GetVMInformation';

$.ajax({
    type: "GET",
    url: serviceURL,
    contentType: "application/json; charset=utf-8",
    dataType: "json",
    success: function (result) {
        alert("This Works fine");
        $("#testDiv").html(result); // Display the partial View in this div
    },
    error: function (XMLHttpRequest, textStatus, errorThrown) {
        alert(errorThrown);
    }
});

My Action then returns a partial view and an list object.

public ActionResult GetVMInformation()
{
    List<VmInfo> VMListArray = new List<VmInfo>();
    ... Code ...
    return PartialView("_List", VmList);
}

The Action gets called and the partial View works. I tested it. So the problem is, my ajax function isnt successful. So it throws an error. When I alert the error I just get "Internal Server Error".

Does anyone see my mistake?

Note: My partial view. Not sure if its important

<!--This partial View is just for testing the ajax function-->

@model IsolutionsAzureManager.Models.VmData

<p>@Model.Name[0]</p>

UPDATE:

So I changed the return type of my function (which has now the type JsonResult) to Json

    JavaScriptSerializer jss = new JavaScriptSerializer();

    string output = jss.Serialize(VmList);
    Response.Write(output);
    Response.Flush();
    Response.End();
    return Json("_List", output);

The good news: The ajax call is now successful. The bad news: I still can't display my partial View. The return value (result) is just [object, Object]

    success: function (result) {
        $("#testDiv").html(result);
    },

I have to give a presentation on my Android game on Friday and just wanted to know exactly where MVC is used in my game. Right now it uses 4 classes: MyGdxGame, GameObject (abstract) Player (extends GameObject, implements inputProcessor), Platform (extends GameObject)

Player jumps when screen is tapped or dashes when screen is dragged.

So right now I know that Player is my Model.

I'm guessing MyGdxGame is my View (2 methods - create() and render())

Where is my controller? Also have I implemented the Observer/observable pattern by using InputProcessor in Player? Here is an example of how I used it:

@Override
public boolean touchDragged(int screenX, int screenY, int pointer) {
    if (isDragged == false && allowDash == true) {
        isDragged = true;
        dash();

    }
    isDragged = false;
    setxSpeed(4.6f);
    return false;
}

Any insight is highly appreciated (and thanks in advance)

I want different designs/layouts and save them in database and Replace {renderaction1} with @{Html.RenderAction("Index","render1");} and {renderaction2} @{Html.RenderAction("Index","render1");} (can be more/less or types)

The reason, I want to have different design for every customer with a dynamic content. For example customer1 want to have 2 select lists and 1 comment field customer2 want to have 1 select list and 1 chart. Any tip how to make it smart and good?

From database

<table>
  <tr><td>Text1</td></tr>
  <tr>
    <td>{renderaction1}</td>
    <td>{renderaction2}</td>
  </tr>
</table>

After replace

<table>
  <tr><td>Text1</td></tr>
  <tr>
    <td>@{Html.RenderAction("Index","render1");} </td>
    <td>@{Html.RenderAction("Index","render2");}</td>
  </tr>
</table>

I am trying to attach a file from my server to an email attachment using Server.MapPath

When I run the code I get the following error

Could not find a part of the path Error

string docOutputPath = Server.MapPath("~/Content/Invoice/fileneame.docx");

I using MVC5 to generate a model with some custom field. I have a field Region each person can Add a record based on his Region. In my View I added :

<div class="form-horizontal">
        <h4>Employee</h4>
        <hr />
        @Html.ValidationSummary(true, "", new { @class = "text-danger" })

        <div class="form-group">
            @Html.LabelFor(model => model.Region, htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">

                @if (User.IsInRole("RiyadhAdminAssistant"))
                {

                    @:Riyadh

                }
                @if (User.IsInRole("JeddahAdminAssistant"))
                {
                   @:JEDDAH

                }
                @if (User.IsInRole("AlAhsaAdminAssistant"))
                {
                    @*<text><b>AlAhsa</b></text>*@
                    @:AlAhsa

                }


            </div>
        </div>

All things appear good to me BUT the values for Region is not stored in the DataBase! how can save it. Any Help please

Thanks in advance.

I have been struggling with what seems to me to be a simple thing. I need to create a form with list of lists.

This is the model that i want to make a form of:

    public OrderViewModel()
    {
        DeliveryAddress = new ProjectDeliveryAddressViewModel();
        OrderItems = new List<OrderItemView>();
    }

    public int ProjectDeliveryId { get; set; }
    public long ProjectId { get; set; }
    [Display(ResourceType = typeof(Res.ViewModels.Common), Name = "CustomerOrderNumber")]
    public string CustomerOrderNumber { get; set; }

    [Display(ResourceType = typeof(Res.ViewModels.Common), Name = "DeliveryDate")]
    public string RequestedDeliveryDate { get; set; }
    public ProjectDeliveryAddressViewModel DeliveryAddress { get; set; }

    public IList<OrderItemView> OrderItems { get; set; } 
}



public class OrderItemView
{
    public OrderItemView()
    {
        Additionalitems = new List<AdditionalItem>();
    }

    public long ProjectItemId { get; set; }
    public string ItemName { get; set; }
    public string ImageData { get; set; }
    public int Quantity { get; set; }
    public decimal Price { get; set; }
    public string AaCompany { get; set; }
    public string SupplierName { get; set; }
    public int SupplierModelId { get; set; }
    public IList<AdditionalItem> Additionalitems { get; set; } 
}

public class AdditionalItem
{
        public string Name { get; set; }
        public string Id { get; set; }
        public bool Value { get; set; }
        public decimal Price { get; set; }
        public int Quantity { get; set; } 
}

What is the simplest way of doing this so that i can easiliy post the form to my mvc controller late on?

below method lstImprtlogisticare is the object having data above 100kb. If the object having below 100kb data it is working fine.If more than 100kb getting communication exception as

The communication object, System.ServiceModel.Channels.ServiceChannel, cannot be used for communication because it is in the Faulted state.

an the code is

public int ImportLogistiCareData(List<Importlogisticare> lstImportlogisticare, int VendorId, TransportationVendorTypes vendorType)
        {
            try
            {
                using (LINAServiceClient oLINAServiceClient = new LINAServiceClient())
                {
                    Mapper.CreateMap<Importlogisticare, IMPORTLOGISTICARE>()
                        .ForMember(dest => dest.ID, opts => opts.MapFrom(src => src.ID))
                        .ForMember(dest => dest.REGION, opts => opts.MapFrom(src => src.Region))
                        .ForMember(dest => dest.TRIPID, opts => opts.MapFrom(src => src.Trip_Id))
                        .ForMember(dest => dest.JOBNO, opts => opts.MapFrom(src => src.Job_No))
                        .ForMember(dest => dest.DATEOFSERVICE, opts => opts.MapFrom(src => src.Dateof_Service))                      
                        .ForMember(dest => dest.DATEOF_BIRTH, opts => opts.MapFrom(src => src.Dateof_Birth))
                        .ForMember(dest => dest.AGE, opts => opts.MapFrom(src => src.Age))
                        .ForMember(dest => dest.HOME_PHONE, opts => opts.MapFrom(src => src.Home_Phone));
                    IMPORTLOGISTICARE[] oIMPORTLOGISTICARE = Mapper.Map<IMPORTLOGISTICARE[]>(lstImportlogisticare);

                    return oLINAServiceClient.ImportFile(null, oIMPORTLOGISTICARE, VendorId, Convert.ToInt32(lstImportlogisticare[0].LASTUPDATEDBY), vendorType);

                }
            }           
            catch (System.ServiceModel.CommunicationException)
            {
                throw;
            }
            catch (Exception)
            {
                throw;
            }
        }

Having read this question, I found the answers outdated/depreciated and hence am asking if anyone would have any 'updated' answers to:

Does JQuery have a function call like

$('#myNewDivId').on('create', function(){

});

for a single div, or multiple 'appends':

$('.myNewDivWithClass').on('create', function(){

});

for a dynamically created div?

  • I would rather not include plugins (esp. 'outdated' ones like .livequery() plugin)
  • 'DOMSubtreeModified' seems to be depreciated, and so would there be an alternative?
  • I would need this function to be compatible with (at least) IE 10 + 11.

What I'm looking to do is on create of this 'new element', is to have an ajax call back to my controller to 'replace' this div with a partial view? However, without a jquery method to use, it seems more difficult than expected

I am new to MVC. So far, I succeeded in binding data from database in a drop down list.

How can I get the selected value and pass it to the Controller to be saved in the database?

Here's what I have done so far:

VIEW:

@Html.DropDownList("State", null, new { @class = "dropdown-toggle col-md-9 form-control" })

CONTOLLER: (this is how bound the data in the dropdown list)

  IEnumerable<SelectListItem> states = db.RefState
            .Select(s => new SelectListItem
            {
                Value = s.ID.ToString(),
                Text = s.Name
            });


        ViewBag.AddressType = types;
        ViewBag.State = states;
        return View();

This is how I save it in the database:

    public ActionResult NewAddress(Address data)
    {
        if(ModelState.IsValid)
        {
            var addressData = new Address()
            {
                ZipCode = data.ZipCode,
                StreetNo = data.StreetNo,
                StreetName = data.StreetName,
                Unit = data.Unit,
                Additional = data.Additional,
                Town = data.Town,
                City = data.City,
                StateID = ?,  
                Description = data.Description,
                VendorCode = data.VendorCode

            };

            db.Address.Add(addressData);
            db.SaveChanges();
            ModelState.Clear();
            data = null;
            ViewBag.Message = "Address succesfully added";
            return RedirectToAction("DeliveryInformation", "DeliveryDetail");
        }

        return View(data);
    }

We are using a session to gather products in a basket. This is just a project, and we know this isn't scalable or at all smart, it's just for show. In any case, everytime we add a product from our page, it will be added to the basket on the side through a basket. In this, we have the name, price and quantity. It adds fine as it should, but when we add the same product again it just add it to the list, not increment upon the existing product.

Is there an "easy" way to add some functionality to the existing code to do this, or is it a lost cause?

This is our controller action for adding it:

 [HttpPost]
        public ActionResult Index(Dish dish)
        {
            Basket basket;
            if (Session["Basket"] == null)
            {
                basket = new Basket();
                Session["Basket"] = new Basket();
            }
            else
            {
                basket = (Basket)Session["Basket"];
            }
            BasketItem basketItem = new BasketItem();
            basketItem.DishId = dish.DishId; 
            basketItem.Title = dish.Title;
            basketItem.Number = dish.Number;
            basketItem.Price = dish.Price;

            basket.AddItem(basketItem);

            return RedirectToAction("Index", basket.Items);

     }

This is for showing it in our partial view:

[ChildActionOnly]
        public ActionResult BasketItemsList()
        {


            Basket basket;

            if (Session["Basket"] == null)
            {
                basket = new Basket();
                Session["Basket"] = new Basket();
            }
            else
            {
                basket = (Basket)Session["Basket"];

            }
            return PartialView("_Basket", basket.Items);
        }

I m stucked here very much and it is going some serious.

I have a Gridview which I am using to show the data from the backend. What I did is For inserting the data, I have made a button on top of the Gridview to add the data in the gridview.

Like this:-

<asp:Button ID="btnAdd" runat="server" CssClass="btn btn-prm" Text="Add" Width="75" CausesValidation="true" ValidationGroup="AddNew" OnClick="btnAdd_Click" />

The same is been done for Edit part also.

I have added a checkbox to select the row for the gridview.See my gridview code for better understanding,

<asp:GridView ID="grdCSRPageData" runat="server" Width="100%" border="1" Style="border: 1px solid #E5E5E5;" CellPadding="3"
                AutoGenerateColumns="False" OnDataBound="grdCSRPageData_DataBound" AllowPaging="true" CssClass="hoverTable"
                OnPageIndexChanging="grdCSRPageData_PageIndexChanging" DataKeyNames="Id" OnRowDeleting="grdCSRPageData_RowDeleting" 
                PageSize="5" ShowFooter="true" OnRowEditing="grdCSRPageData_RowEditing" OnRowUpdating="grdCSRPageData_RowUpdating" 
                OnRowCancelingEdit="grdCSRPageData_RowCancelingEdit">
                <AlternatingRowStyle CssClass="k-alt" BackColor="#f5f5f5"/>
                <Columns>
                    <asp:TemplateField HeaderText="Action" HeaderStyle-Width="5%" HeaderStyle-CssClass="k-grid td" >
                        <ItemTemplate>
                            <asp:Checkbox ID="chkSelect" runat="server" AutoPostBack="false" />
                        </ItemTemplate>
                    </asp:TemplateField>
                    <asp:BoundField DataField="page_title"  HeaderText="Page Title" ItemStyle-Width="30" HeaderStyle-CssClass="k-grid td"  />
                    <asp:BoundField DataField="page_description" HeaderText="Page Description" ItemStyle-Width="30" HeaderStyle-CssClass="k-grid td" />
                    <asp:BoundField DataField="meta_title" HeaderText="Meta Title" ItemStyle-Width="30" HeaderStyle-CssClass="k-grid td" />
                    <asp:BoundField DataField="meta_keywords" HeaderText="Meta Keywords" ItemStyle-Width="30" HeaderStyle-CssClass="k-grid td" />
                    <asp:BoundField DataField="meta_description" HeaderText="Meta Description" ItemStyle-Width="30" HeaderStyle-CssClass="k-grid td" />
                    <asp:BoundField DataField="Active" HeaderText="Active" ItemStyle-Width="30" HeaderStyle-CssClass="k-grid td" />
                    <asp:TemplateField HeaderText="Action" HeaderStyle-Width="15%" HeaderStyle-CssClass="k-grid td" >
                        <ItemTemplate>
                            <asp:ImageButton ID="btnDelete" AlternateText="Delete" ImageUrl="~/images/delete.png" runat="server" Width="15" Height="15" CommandName="Delete" CommandArgument='<%# Eval("Id") %>' CausesValidation="false" OnClientClick="return confirm('Are you sure you want to delete this record?')" />
                        </ItemTemplate>
                    </asp:TemplateField>
                    <asp:CommandField ButtonType="Image" ItemStyle-Width="15" EditImageUrl="~/images/edit.png" ShowEditButton="True" ControlStyle-Width="15" ControlStyle-Height="15" CancelImageUrl="~/images/close.png" UpdateImageUrl="~/images/update.png">
                        <ControlStyle Height="20px" Width="20px"></ControlStyle>
                    </asp:CommandField>
                </Columns>
            </asp:GridView>

Now what my requirement is. Whenever I check the checkbox for any row, and click on the Update button, the repsective Row should get open in a popup with the existing data as it is getting for adding the new Row. I tried but couldn't succeed. Please help me with this. Let me know if you need anything else.

Thanks.!

I am stuck with a problem where I have multiple tables in an update panel. I bind the ASP.net gridview items from code behind when I click an ASP.net button. This causes a postback which triggers my javascript pageLoad functions.

Inside the pageLoad block I have following function which gets the length of the table and either displays a detailed view if the length is 2 (one row) or displays the table when the length is more than 2. This works well.

    $(function () {
        var len = $("#<%=gvClave.ClientID%> tr").length;
        if (len > 2) {
            document.getElementById('frameClaveTable').style.display = 'block';
            $('#<%=gvClave.ClientID%>').gridviewScroll({
                width: $('#frameClaveTable').width(),
                height: 200
            });
            $('#sliderClaveTable').animate({ width: $('#frameClaveTable').width() + 50 });
        } else if (len == 2) {
            showClaveDetails($("#<%=gvClave.ClientID%> tr"));
        }
    });

I have a third table in the same update panel which I bind when I search for a value in the SQL database. During the postback when I bind the third table I would expect the other tables to be reset and disappear from view. However in the postback pageLoad event the old table is still found and displayed again. I can't get my head around how to prevent this. I have tried to force a postback prior to refreshing the tables. I have tried to put the tables in seperate update panels but to no avail.

Any ideas on this issues are welcome.

Thanks.

I have a .NET web application on a server (the "proxy server") that relays data from a desktop application (the "streamer") to a client (the "client").

All communication involved uses web calls - that is, the .NET components (the streamer talking to the proxy server) uses WebClients, and the client uses javascript xmlHttp GET requests to retrieve data from the proxy server. It is here wherein my question lies.

A very simple version of the javascript loop is as follows:

var interval = setInterval(function () { getnum(); }, 250);

function getnum() {
    var xmlHttp = null;
    xmlHttp = new XMLHttpRequest();
    xmlHttp.open("GET", "getImage.aspx?param=val", false);
    xmlHttp.send(null);
    var str = xmlHttp.responseText;
    xmlHttp = null;

    // various processing
}

if it matters, the responseText is a base64-encoded string, plus some extra ASCII data to help with the processing.

The streamer application uploads data every 250ms as well. The size of the data being transferred does not exceed 120K per transfer.

The Problem: For the most part, this works. Every now and then, though the server suddenly stops responding to these GET requests. I get a network error, Failed to execute 'send' on 'XMLHttpRequest': Failed to load 'my.site.come/etc...' When this happens, not only does the javascript fail to connect to the server, but other web browsers on other computers can't access the website at all (the root my.site.com). However! Looking at IIS access logs, it appears that the streamer applicaion is still successfully pushing data towards the server. There is no cross site stuff going on, and 90% of the time, this works just fine. I can't figure out what is causing the error to occur. I can't trigger the failure. The only way I can observer it happening is to sit here and watch the javascript calls in the developer console of whatever web browser I'm using (the problem exists across all browsers).

What is happening? And, why would it only fail on occasion?

I'm writing an ASCX control that needs to reference both a JavaScript file and a CSS file.

Obviously, I only want the host page to reference these files once. So I'm using Page.ClientScript.RegisterClientScriptInclude() to reference the JavaScript file. The CSS file, however, is a bit more complicated.

I thought maybe I could do the following:

if (!Page.ClientScript.IsClientScriptIncludeRegistered(ScriptManagerJsKey))
{
    Page.ClientScript.RegisterClientScriptInclude(this.GetType(), ScriptManagerJsKey, ResolveClientUrl("~/javascript/PaymentSchedule.js"));

    HtmlLink cssLink = new HtmlLink();
    cssLink.Href = "~/css/PaymentSchedule.css";
    cssLink.Attributes["rel"] = "stylesheet";
    cssLink.Attributes["type"] = "text/css";
    Page.Header.Controls.Add(cssLink);
}

The idea here was to add an HtmlLink to reference the CSS file in the page header, but only once. Since I believe this code will only add the JavaScript reference once, I thought this would do the trick.

However, this actually adds the reference to the CSS file twice in the head section of the file.

Has anyone found a trick to referencing a CSS file only once from an ASCX control?

I am proficient in MVC 5 but web api 2 is new to me. I am trying to add a webapi controller to my MVC Project, But I can't access It's path. Iv'e added a web api controller in a new Folder called webapi, and the name of the controller is searchcontroller, Inside My MVC 5 Project. I can't access it's path, something that should be: /api/search/get. I think It might be with something with my App Start in Global Ajax :

Help Please! Here is the code in the app start :

protected void Application_Start()
    {
        AreaRegistration.RegisterAllAreas();
        RouteConfig.RegisterRoutes(RouteTable.Routes);
        GlobalConfiguration.Configure(config =>
        {
            config.MapHttpAttributeRoutes();

            config.Routes.MapHttpRoute(
        name: "ApiById",
        routeTemplate: "api/{controller}/{id}",
        defaults: new { id = RouteParameter.Optional },
        constraints: new { id = @"^[0-9]+$" }
    );

            config.Routes.MapHttpRoute(
                name: "ApiByName",
                routeTemplate: "api/{controller}/{action}/{name}",
                defaults: null,
                constraints: new { name = @"^[a-z]+$" }
            );

            config.Routes.MapHttpRoute(
                name: "ApiByAction",
                routeTemplate: "api/{controller}/{action}",
                defaults: new { action = "Get" }
            );
        });

The controller code :

 public class WebAPISearchReultsController : ApiController
{
    public IEnumerable<ICE.Logic.ArticleSearchResult> Get(string searchQuery)
    {
        return SearchLogic.Instance.GetArticleSearchResults(searchQuery);
    }
}

I have an Account controller with two Get methods, one that gets all accounts and takes no input, and another that takes an Id int and returns that specific account.

The project constraints are that we can't have id as an optional parameter on the default route, but instead need get-one-account and get-all-accounts to be accessed via different routes, and we can't use attribute routing. So our route configuration currently looks like this:

config.Routes.MapHttpRoute("AccountWithId", "api/account/{id}", new { action = "Get", id = RouteParameter.Optional }
                , new { httpMethod = new HttpMethodConstraint(HttpMethod.Get), id = @"\d+" });

config.Routes.MapHttpRoute("Default", "api/{controller}");

My two Get methods on the AccountController look like this:

public IHttpActionResult Get()
        {
            IList<AccountDto> users = m_service.Get();

            return Ok(users);
        }

        public IHttpActionResult Get(int accountId)
        {
            AccountDto user = m_service.Get(accountId);

            return Ok(user);
        }

But when I call Get with an id parameter in my test via my custom route and debug as below, it's still hitting the Get method that doesn't take an id parameter and returns all.

var url = "http://test/api/account/" + accountId;

var response = await m_server.HttpClient.GetAsync(url);

Any idea why?

If the end user scrolls down a page, I would like to move the page back to the top with a button click. The user clicks the button, and I do validation. The error message is at the top of the page, and the button is at the bottom of the page. If something is invalid, then I want to send the user scroll back to the top of the page so they can see the error message.

How can I do this? I don't want to use java-script, unless I have to. Is there away to do this in C# from the code behind?

I have tried this:

ScriptManager.RegisterStartupScript(Page, this.GetType(), "ScrollPage", "scrollToTop();", true);

At run time I get the error: 0x800a1391 - JavaScript runtime error: 'scrollToTop' is undefined

I have a textbox that a user inputs time 24:00 format.

$("[id*=TxtTransactionTime]").mask("99:99");

This is the jquery I have to mask that function.

For example if user inputs:

1300 the mask will turn this into 13:00 This works great!

The problem results from when a user puts something like this:

"4:56" the mask will turn that into "45:6" (i would like the mask to pad the left with a zero so instead it's like this: 04:56)

or if the user inputs:

45:6 the mask won't do anything, but I would like it to do this => 45:60 and pad the right with a zero.

Thank you for your assistance!