How can I get getTimezoneOffset(); value from the client side in codebehind(aspx.cs file) on Page_load event?
I don't believe you can do this directly. I would have thought you could grab the Date from the Request.Headers and calculate this, but, at least in my environment, using my browser, the Date header is not accessible.
The only possible solution I can think of, since client info is typically limited to what's sent in the headers or in a form request would be to use Javascript to grab the headers, populate a form field (maybe a HiddenField) and trigger a postback.
I googled it and came up with this response, which shows pretty much how to do it the way I was thinking you'd need to - slightly differently than I would have done it, but close enough.
http://www.velocityreviews.com/forums/t70226-client-timezone.html
The code for the answer on that link is here:
<td>
<input type="button" value="getclientutc" onclick="GetClientUTC()">
<input type="hidden" id="hdClientUTC" runat="server">
</td>
:
function GetClientUTC()
{
var now = new Date()
var offset = now.getTimezoneOffset();
document.Form1.hdClientUTC.value = offset
}
</script>
Related
The client should be able to send everything with a button, so I can do the following:
Send everything as form fields named like invoiceId_detail_text where invoiceId would be the id of the invoice, detail the part, and text the kind of field.
Example:
<form id="invoices" name="invoice">
#foreach(var Invoce in Model.Invoices) {
<div>
<input type="number" id="#String.Format("{0}_amount", Invoice.InvoiceId)"/>
</div>
/*More Input Fields for the Invoice*/
<div>
<button type="submit"></button>
</div>
}
</form>
Or I can put every invoice separated in its own form, and send them by ajax, every form success I send the next one and so on.
Example:
#foreach(var Invoice in Model.Invoices) {
string formName = String.Format("{0}_form", Invoce.InvoceId);
<form id="#formName" class="invoiceForm" id="#formName" action="#Url.Action("EditIndividualInvoice","InvoicingEdit")">
<input type="hidden" name="InvoiceId" value="#Invoice.InvoiceId"/>
<div>
<input type="number"/>
</div>
/*More Input Fields for the Invoice*/
</form>
}
<button type="button" onclick="SendAllForms();">Send</button>
I did some research between some of my co-workers and many of them told me to just go with a post with all the invoices at the same time and then access every field by item id because I don't have knowledge of how many invoices are going to be sent, but i can get all of them by class on JQuery so it shouldn't be a problem.
I also read this article from a UX point of view and it keeps me thinking about it.
By doing it with AJAX the cliend could be able to see a loading bar and it would be great, but if he closes the page the request would be incomplete and it could be complicated.
Which option could be better and why and what are the security implications of using one over another?
I think the solution depends principally of the behavior that you wish.
By doing it with AJAX the cliend could be able to see a loading bar and it would be great, but if he closes the page the request would be incomplete and it could be complicated.
In the 2 solutions, if the user closes the page after clicking the button, this will not cancel the save. Once the request sent, it cannot be cancelled. So you shouldn't have "security" problems whatever the choosen solution.
The only thing you need to be careful, is to disable all AJAX buttons during an AJAX request, to avoid the user sending several request in the same time (that can provoke saving inconsistency data).
The classic solution is generally most simple to implement.
The AJAX solution can be most complicated to implement (more code), but provides a friendliest behavior.
I've had a look over a couple of the other questions on the site and cant find anything that exactly answers what I'm looking to do. To help I'll give a bit of background.
I've recently started experimenting with ASP.NET and MVC4. As my first real attempt at building something useful I am building a web application that will allow me to record and track my workouts in the gym. I have got the basis of all my models/controllers/views etc. The part I am having trouble with is the actual layout of the page to record workouts. Each Workout is made up of a list of Sets (The sets contain information like Exercise, Weight, No of Repetitions etc.... Now the way I want this to work on the WebApp is for a user to be able to hit a button for adding a set. This will then load a a section below without a page re-load that allows them to enter information about that set. They can hit the same button again to record a second set so on and so forth....
They will then hit a save button and I need to loop through each "Set" that has been added and save the information to a database.
I think it should be possible, just not exactly sure how to achieve it. The way I would do it in a standard Windows Application is using UserControls, I am thinking maybe Partial Views in ASP.NET and MVC?
Any ideas guys?
Any more questions let me know.
We did something similar with MVC5, maybe you can figure something out from here.
We used AJAX and PartialViews, at first the page loads we load a table with some initial content, and an Add Option button. When the user hits the button, we increment the current count and add another row to the table via an action which returns a partial view.
<script>
var currentCount = 1;
$(document).ready(function () {
$("#AddOptionButton").click(function () {
var CountryOptions = {};
CountryOptions.url = "AddOption";
CountryOptions.type = "POST";
CountryOptions.datatype = "text/html";
CountryOptions.data = JSON.stringify({count: currentCount });
CountryOptions.contentType = "application/json";
CountryOptions.success = function (html) {
$("#attributesList tr:last").after(html);
currentCount = currentCount + 1;
};
$.ajax(CountryOptions);
});
});
</script>
<table id="attributesList">
<tr>
<th>#</th>
<th>Name</th>
</tr>
<tr>
<td>1.</td>
<td><input type="text" name="optionInput[0]" value="Option 1" /></td>
</tr>
</table>
<input type="button" name="AddOptionButton" id="AddOptionButton" value="Add 1 More" />
<input type="submit" value="Submit Form" />
Our partial view will get the current count as input and returns something like below
<tr id="NewRow1">
<td>2.</td>
<td><input type="text" name="optionInput[1]" value="New Option Value"/></td>
</tr>
Note that we are getting an array of optionInput when the form is submitted. We can easily save the data by looping through the inputs.
You said "without a page re-load". You can do that by using AJAX. It sounds like you have to do much fundamental education to reach your goals. I want to suggest you to work into JavaScript and understand the difference between client-side and server-side in the world of web development. In addition it is important to know the behaviour of HTTP (requests, responses, etc..).
After that, you are able to load content from the server asynchronously using and ajax request. You can do that easily using jQuery. Example here:
$.ajax({
type: 'post',
url: '/Controller/Action',
data: {CustomerName: 'James', AdditionalData: ... },
dataType: 'JSON',
success: function() {
// do anything after request success
}
});
With JavaScript you are able to create an communication between server and client and manipulate the DOM of the client.
Ok,
i have a fully rendered dynamic form ( i do not know the content of the form, it is provided to my via a webservice )
i used asp.net RequiredFieldValidator for validation, because i read in this article that we could dynamically switch validators on and off depending if the field is visible or not
with the ValidatorEnable(val, enabled) function.
though now that i got the form rendered, i'm running into a bit of trouble with this javascript, as i don't want to put it in the aspx file itself, (don't have a control there anyway since the form is build up in codebehind from the webservice data...)
so i took a look at the clientId and it turns out the validator's client ID is the id of the span it renders to.
so i tried running this in firebug to test if i could enable / disable one of those validators, but that seems not to be possible, a jQuery span element does not have a property to enable it.
ValidatorEnable($("#ContentPlaceHolderDefault_MasterWithNavContent_Poll_4_reqAnswer_373ac8b7_8da9_467b_b9b4_d586e45a7504"), false);
and the html that goes with this
<div class="question-container question-odd" id="ContentPlaceHolderDefault_MasterWithNavContent_Poll_4_question-373ac8b7-8da9-467b-b9b4-d586e45a7504">
<div class="question-meta">
<h3 class="validation-label">Which club have you visited?</h3>
<span style="display: block; margin-bottom: 10px; margin-top: 5px;" class="error validation" id="ContentPlaceHolderDefault_MasterWithNavContent_Poll_4_reqAnswer_373ac8b7_8da9_467b_b9b4_d586e45a7504">Please fill out this field.</span>
</div>
<input type="text" class="answer-container text" id="ContentPlaceHolderDefault_MasterWithNavContent_Poll_4_answer_373ac8b7_8da9_467b_b9b4_d586e45a7504" name="ctl00$ctl00$ctl00$ContentPlaceHolderDefault$MasterWithNavContent$Poll_4$answer_373ac8b7_8da9_467b_b9b4_d586e45a7504">
</div>
Does someone know where i'm going wrong here?
maybe I'm to quick to jump from the serverside ClientId to the <span> which the RFV renders into? but they seem exactly the same.
hope someone can point me in the good direction!
Maybe a better approach would be to loop through the client-side array of validators (Page_Validators) and find the validator which you want to disable.
See also this MSDN page and this codeproject article for more information.
Perhaps a more appropriate way to do this would be
ValidatorEnable($("<%= reqAnswer.ClientID %>")[0], false);
Using <%= reqAnswer.ClientID %> avoids having to guess at or hard-code the client-side ID of the validator. Adding [0] after the jQuery $() gets the actual validator DOM element instead of the jQuery wrapper.
Source for [0]
I am trying to submit a form to a handler page but nothing is working now, it doesn't even hit the handler...
Here is my code :
<form action="Unsubscription.ashx?actionmethod=subscribe" method="get" >
<div class="h1">
<input type="text" class="input" value="enter your e-mail" name="ekey" />
<input type="submit" value="Submit" />
</div>
</form>
handler code :
public void ProcessRequest(HttpContext context)
{
try
{
string email = context.Request.Params["ekey"];
switch (context.Request.Params["actionmethod"])
{
case "subscribe":
NewsLetter.Subscribe(email);
break;
case "unsubscribe":
NewsLetter.Unsubscribe(email);
context.Response.ContentType = "text/html";
context.Response.Write("your subscription has been successfully canceled. thanks.<br/><a href='http://www.kayatax.com'><b>home page</b></a>");
break;
}
}
catch {
context.Response.ContentType = "text/html";
context.Response.Write("This e-mail doesn't exist in our database. Thanks.<br/><a href='http://www.kayatax.com'><b>Home Page</b></a>");
}
}
Your </<form> tag is malformed for a start. Make it </form>, as I'm sure you know.
If you have browser-side rendering problems, and you're not hitting your server-side handler, I'd investigate the browser side first. See what is getting transmitted over the wire: in Firebug, enable the Net panel, reload the page, submit the form and then look at the Request in the Net panel. Hover over the first node (the request to the form-handler page) and make sure the request URL is as you expect. Then expand the node and look at the Request headers.
The first thing I'm wondering, not seeing more of your web-app, is whether the target Unsubscription.ashx is in the same directory as the page with the form, or if there's a routing method of some sort that makes it look that way. You're using a document-relative URL; are you sure the target is where you think it is?
By the way, you should not use the GET method for form submissions that change data on the server; use POST for that. It's a bit more work, but much safer. GET requests should be idempotent. If you use GET to trigger an action that changes things on the server, you may find they're changed when you don't expect them to be. D'oh!
Your form is using 'get' which essentially is HTTPGET. Check the submitted URL and querystring. It should be
Unsubscription.ashx?actionmethod=subscribe&ekey=enter%20your%20email
is it showing correctly?
You do not have a name for your input-submit button, but that shouldn't affect what you want.
I am interested to know what specifically Page.IsPostBack means. I am fully aware of it's day to day use in a standard ASP.NET page, that it indicates that the user is
submitting data back to the server side. See Page:IsPostBack Property
But given this HTML
<html>
<body>
<form method="post" action="default.aspx">
<input type="submit" value="submit" />
</form>
</body>
</html>
When clicking on the Submit button, the pages Page_Load method is invoked, but the Page.IsPostBack is returning false. I don't want to add runat=server.
How do I tell the difference between the pages first load, and a Request caused by the client hitting submit?
update
I've added in <input type="text" value="aa" name="ctrl" id="ctrl" /> so the Request.Form has an element, and Request.HTTPMethod is POST, but IsPostBack is still false?
Check the Request.Form collection to see if it is non-empty. Only a POST will have data in the Request.Form collection. Of course, if there is no form data then the request is indistinguishable from a GET.
As to the question in your title, IsPostBack is set to true when the request is a POST from a server-side form control. Making your form client-side only, defeats this.
One way to do this is to extend the ASP.NET Page class, "override" the IsPostBack property and let all your pages derive from the extended page.
public class MyPage : Page
{
public new bool IsPostBack
{
get
{
return
Request.Form.Keys.Count > 0 &&
Request.RequestType.Equals("POST", StringComparison.OrdinalIgnoreCase);
}
}
}
In the example that you include in your question, there is no viewstate involved; there is no way for the server to link this request to a previous request of the page and treat them as a unit. The request resulting in clicking the button will look like any other random request coming in to the server.
Generally a you could view a PostBack as a combination of:
HTTP request method equals "POST"
HTTP header HTTP_REFERER equals the current URL
That's not 100% foolproof tho, it does not take into account any state of any kind (which you probably want even if you don't know it) but it is a post, back to the current page.
You could check the headers to see if your input controls are returning a value (using Request.Forms as tvanfosson points out). However, the really big question is why you would not want to add runat=server. The entire page processing edifice implemented by ASP.NET (except MVC) depends on processing the page output through the server to set up the appropriate client-side code for callbacks, etc.