how to set a default dropdownlist selecteditem - c#

I have a login page where user enters Username(textbox), Password(textbox), and location(dropdownlist) then login.
On the server page, for the location dropdonwlist I have a connection string to access SQL server database to get all locations from location table and bound the data to the dropdownlist.
For the dropdownlist.SelectedItem, What I want to do is that once user enters Username, onChange, the default location for the particular user should be the selected location before the user clicks Login. This default location is defined by locationID(FK) in the Login table which has loginId, username, password, and locationID as its columns. I want the process of retrieving locationID (accessing a DB table) to happen on the server side, then pass the locationID to the client side where I can call a function to select a default dropdownlist item according to the locationID. What's the way to accomplish this?? Thanks
Programming Language C#
Database SQL Server 2005

There are two ways to get this done: AJAX or Postback. AJAX would be the nicer way and postback would be the easier way, it's up to you really...
Both ways would take the username and run a query against the db to get the locationid and then select it from the dropdown.
Logically however this can be a security hole (unless running internally) where a hacker could generate random usernames and see if they return a valid location since a passwrod is not needed. Which leads me to question why you need to select a location if it's in the db already? You can just select it when validating the user...

Which is tied more closely to a 'location': the user or the computer?
If it's appropriate to pick a default location for a computer instead of a user,
you could consider using a cookie to store the default location. Some advantages:
No javascript required - Drop down default is selected by the server.
Single request - The cookie value is included in the GET request.
It would be relatively easy to implement with some caveats:
A cookie is scoped to the client computer's (windows) user account. If you have two users on the same computer (as same user) with different locations, then this isn't a good solution.
Sometimes browsers have cookies turned off.

I'd probably use jQuery, with a method that's triggered by onBlur for the username box. This method would call an AJAX method on your page to get the default Location ID from the database.
Depending on what version of .NET you're running you can either use AjaxPro or the ASP.NET AJAX Toolkit to expose public methods. (I've found AjaxPro to be a little easier to use).
Then it's just a matter of writing the jQuery:
(Very rough code here, I probably got a lot of things wrong. If you expose the method with the Ajax Toolkit)
function doSomething()
{
var username = $.("#textbox").val();
$.ajax({
type: "POST",
url: "default.aspx",
data: "username=" + username,
success: function(result){
// Select the proper option here based on the result
$.("#dropdown").val(result);
}
});
}
AjaxPro is a little different as it generates page JavaScript which you can call to get the result.

Related

unable to get complete url after # using query string in asp.net c# [duplicate]

I know on client side (javascript) you can use windows.location.hash but could not find anyway to access from the server side. I'm using asp.net.
We had a situation where we needed to persist the URL hash across ASP.Net post backs. As the browser does not send the hash to the server by default, the only way to do it is to use some Javascript:
When the form submits, grab the hash (window.location.hash) and store it in a server-side hidden input field Put this in a DIV with an id of "urlhash" so we can find it easily later.
On the server you can use this value if you need to do something with it. You can even change it if you need to.
On page load on the client, check the value of this this hidden field. You will want to find it by the DIV it is contained in as the auto-generated ID won't be known. Yes, you could do some trickery here with .ClientID but we found it simpler to just use the wrapper DIV as it allows all this Javascript to live in an external file and be used in a generic fashion.
If the hidden input field has a valid value, set that as the URL hash (window.location.hash again) and/or perform other actions.
We used jQuery to simplify the selecting of the field, etc ... all in all it ends up being a few jQuery calls, one to save the value, and another to restore it.
Before submit:
$("form").submit(function() {
$("input", "#urlhash").val(window.location.hash);
});
On page load:
var hashVal = $("input", "#urlhash").val();
if (IsHashValid(hashVal)) {
window.location.hash = hashVal;
}
IsHashValid() can check for "undefined" or other things you don't want to handle.
Also, make sure you use $(document).ready() appropriately, of course.
[RFC 2396][1] section 4.1:
When a URI reference is used to perform a retrieval action on the
identified resource, the optional fragment identifier, separated from
the URI by a crosshatch ("#") character, consists of additional
reference information to be interpreted by the user agent after the
retrieval action has been successfully completed. As such, it is not
part of a URI, but is often used in conjunction with a URI.
(emphasis added)
[1]: https://www.rfc-editor.org/rfc/rfc2396#section-4
That's because the browser doesn't transmit that part to the server, sorry.
Probably the only choice is to read it on the client side and transfer it manually to the server (GET/POST/AJAX).
Regards
Artur
You may see also how to play with back button and browser history
at Malcan
Just to rule out the possibility you aren't actually trying to see the fragment on a GET/POST and actually want to know how to access that part of a URI object you have within your server-side code, it is under Uri.Fragment (MSDN docs).
Possible solution for GET requests:
New Link format: http://example.com/yourDirectory?hash=video01
Call this function toward top of controller or http://example.com/yourDirectory/index.php:
function redirect()
{
if (!empty($_GET['hash'])) {
/** Sanitize & Validate $_GET['hash']
If valid return string
If invalid: return empty or false
******************************************************/
$validHash = sanitizeAndValidateHashFunction($_GET['hash']);
if (!empty($validHash)) {
$url = './#' . $validHash;
} else {
$url = '/your404page.php';
}
header("Location: $url");
}
}

How to get data from a client on load?

I'm aware that data can be passed in through the URL, like "example.com/thing?id=1234", or it can be passed in through a form and a "submit" button, but neither of these methods will work for me.
I need to get a fairly large xml string/file. I need to parse it and get the data from it before I can even display my page.
How can I get this on page load? Does the client have to send a http request? Or submit the xml as a string to a hidden form?
Edit with background info:
I am creating a widget that will appear in my customer's application, embedded using C# WebBrowser control, but will be hosted on my server. The web app needs to pass some data (including a token for client validation) to my widget via xml, and this needs to be loaded in first thing when my widget starts up.
ASP.NET MVC 4 works great with jQuery and aJax posts. I have accomplished this goal many times by taking advantage of this.
jQuery:
$(document).ready(function() {
$.ajax({
type: "POST",
url: "/{controller}/{action}/",
data: { clientToken: '{token}', foo: 'bar',
success: function (data, text) {
//APPEND YOUR PAGE WITH YOUR PARSED XML DATA
//NOTE: 'data' WILL CONTAIN YOUR RETURNED RESULT
}
});
});
MVC Controller:
[HttpPost]
public JsonResult jqGetXML(string clientToken, string foo)
{
JsonResult jqResult = new JsonResult();
//GET YOUR XML DATA AND DO YOUR WORK
jqResult.Data = //WHATEVER YOU WANT TO RETURN;
return jqResult;
}
Note: This example returns Json data (easier to work with IMO), not XML. It also assumes that the XML data is not coming from the client but is stored server-side.
EDIT: Here is a link to jQuery's Ajax documentation,
http://api.jquery.com/jQuery.ajax/
Assuming you're using ASP.NET, since you say it's generated by another page, just stick the XML in the Session state.
Another approach, not sure if it helps in your situation.
If you share the second level domain name on your two sites (i.e. .....sitename.com ) then another potential way to share data is you could have them assert a cookie at this 2nd level with the token and xml data in it. You'll then be provided with this cookie.
I've only done this to share authentication details, you need to share machine keys at a minimum to support this (assuming .Net here...).
You won't be able to automatically upload a file from the client to the server - at least not via a browser using html/js/httprequests. The browser simply will not allow this.
Imagine the security implications if browsers allowed you to silently upload a file from the clients local machine without their knowledge.
Sample solution:
Background process imports xml file and parses it. The background process knows it is for customer YYY and updates their information so it know the xml file has been processed.
A visitor goes to the customer's web application where the widget is embedded. In the markup of the widget the customer token has been added. This could be in JavaScript, Flash, iFrame, etc.
When the widget loads, it makes a request to you app which then checks to see if the file was parsed for the provided customer (YYY) if it has, then show the page/widget.
If the XML is being served via HTTP you can use Liqn to parse the data.
Ex.
public partial class Sample : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
string url = "http://news.yahoo.com/rss/";
var el = XElement.Load(url).Elements("channel");
StringBuilder output = new StringBuilder();
foreach (var c in el.Elements())
{
switch (c.Name.LocalName.ToLower())
{
case "title":
output.Append(c.Value);
output.Append("<br />");
break;
}
}
this.Label1.Text = output.ToString();
}
}
It is not exactly clear what the application is and what kind of options you have, and what kind of control over web server you have.
If you are the owner of the web server/application your options are way wider. You can first send a file to web-server with HTTP POST or PUT, including a random token, and then use the same token for GET with token in the query string
or use other options, applicable to third party-owned websites
if you are trying to consume some auth api, learn more about it. since you are hosting web browser control, you have plenty of options to script it. including loading whatever form, setting textarea or hidden field text with your xml and then simulating a submit button click. you can then respond to any redirects and html responses.
you can also inject javascript inside the page that would send it to server with ajax request.
the choice heavily depends on the interaction model.
if you need better advice, it would be most helpful if you provided sample/simplified url/url pattern, form content, and sequence of events that is expected from you from code/api/sdk perspective. they are usually quite friendly.
There are limited number of ways to pass data between pages. Personally for this I would keep in session during the generating page and clear it when it is retrieved in the required page.
If it is generated server side then there is no reason to retrieve it from client side.
http://msdn.microsoft.com/en-us/library/6c3yckfw(v=vs.100).aspx
Create a webservice that your C# app can POST the XML to and get back HTML in response. Load this HTML string into the WebBrowser control rather than pointing the control to a URL.

Passing parameters using Server.Transfer but not using query string

I have a registration form and want to transfer the user to the success page, telling him that an email was sent to his email. I need to transfer his email from the register page to the success page.
I found about Server.Transfer, but I can't find out how to send parameters. I don't want to use query string as I don't like revealing information in the URL.
What is the proper way (if possible) to do this?
Server.Transfer("destination.aspx", true)
You might see that the above code contains the name of the page to which the control is transferred and a Boolean value ‘True’ to indicate to preserve the current form state in the destination page.
Set a property in your login page and store in it, the email.
Once this is done, do a Server.Transfer("~/SuccessPage.aspx", true);
On the other page, where you redirected, you should check something like that :
if(this.PreviousPage != null) {
((LoginPageType)this.PreviousPage).MyEmailProperty;
}
When you using server transfer you just move execution to different server handler , user will no see the new url or the parameters so it safe to make this transfer.
I would rather recommend that you do it differently.
When the user clicks the register button, you verify it all and then send the email from the still current page (so you need not transfer data to another page at all). If all went well, you just redirect:
Response.Redirect("/order/success.aspx");
If something was wrong (validation errors, sending email caused an exception) you are still on the right page for a retry. I would not use Server.Transfer at all in most cases.
You'll have to persist the value somewhere. The obvious options are in the Session object, or in a database.
For this kind of use case. You can use Context.Items to save the data with a key and read the value using the same key in the child page you are doing the Server.Transfer. Context.Items are sort of per request scoped cache for you.
Context.Items['DataKey'] = Data;
Server.Transfer("~/AnyRouteRelativePath", true);

How can i get the Logged in user Name of Client machine

How can i get the LoggedIn in user Name of Client machine
without client providing the useid and password...
(wjen the users visits the page i need to get In which user Id he/she loggedIn)
I tried
string clientMachineName;
clientMachineName = (Dns.GetHostEntry(Request.ServerVariables["remote_addr"]).HostName);
Response.Write(clientMachineName);
If you're in a domain environment you could enable Windows Authentication which will allow the users to bypass explicitly logging on in favor of NTLM authentication. IE and Chrome work well with this out of the box, FF has a config setting for it.
EDIT
If you only care about browsers/OSs that support ActiveX then you can get it using Javascript with specific ActiveX privileges (from here):
<script type="text/javascript">
<!--
var WinNetwork = new ActiveXObject("WScript.Network");
alert(WinNetwork.UserName);
//-->
</script>
Try this
Might be its work as per your requirement
Request.ServerVariables["LOGON_USER"]
if Request.ServerVariables("LOGON_USER") Returns Empty String in ASP.NET
Microsoft Guidline for that
You can use Request.LogonUserIdentity for getting client details.
Response.Write(Request.LogonUserIdentity.Name);
It seems ServerVariables have been depreciated for C# in some instances.
If so, you'll need to do it this way:
string login = System.Security.Principal.WindowsIdentity.GetCurrent().Name;
If you really want to use ServerVariables, keep in mind they are CaSe Sensitive in C#. The correct casing is almost always UPPER, and here is the list of them:
List of ServerVariables

Verify E-mails as they are typed

On my page a users (internal staff members) can type a comma separated list of e-mail addresses. What I would like to do is every time a comma is typed it checks that the newly written e-mail address is in the address book.
Currently I have the address book stored as a Hashtable for O(1) search times but I can easily switch to another data structure if it is recommended.
You can do that with JavaScript and AJAX to communicate with the server side.
You can do the next steps:
Create a web service that gets the string from the client (which is the email the user has typed), checks it and returns true/false.
Add [ScriptService] attribute to the
web service class.
On the page, add an ASP.NET
ScriptManager control with
Scripts/ScriptReference that points to the web service from step 1.
On the page, add javascript code that hooks to the onkeydown event of the emails textbox
In this event handler, if the user types a comma, execute a web service request to the server with the textbox value. When the respond (true or false) is received, do whatever you need with it.
You can read more on MSDN here and here.
You might also find helpful the AutoComplete AJAX extender.
In order for it to be done on keypress there is going to be javascript (or client side vbscript if you're using IE) involved. This cannot be done without it if you're looking to do it based on keyed input.
If you were to do it when the user leaves that text box, then you could use AutoPostback and code it in C# on the server side - I have to say though, I think that approach is ugly. Requiring a synchronous postback to validate data is a huge imposition on the user in my opinion and therefore should only really be a last resort or a stopgap while you're getting asynchronous script to do the work. You could also do it at post time (when they're trying to submit the form) and validate them and give the user back a validation message if any of the addresses fail, but once again, this is synchronous and the user doesn't get the benefit of early feedback.
I would do this using either a Windows Service (or use RESTful service) using a javascript call (using the XmlHttpRequest object). Bind your textbox's keydown event to a JavaScript method.
<input type="text" onKeyDown="javascript:CheckInput(this)" />
Then set up your javascript call - this is the guts of what's going on:
(Disclaimer: This code is not production ready, it's merely an example that should give you some direction)
var req;
function CheckInput()
{
if (window.event) keycode = window.event.keyCode;
if (keycode == 188) //KeyCode 188 = Comma;
{
//I haven't provided code for this, you will need to code
//the extraction of the address you wish to test for yourself...
var addressToCheck = ParseLastAddressFromTextBox();
req = new XMLHttpRequest();
//Replace <SERVICEADDRESS> with the URL of your web service
//the 'true' parameter specifies that the call should be asynchronous
req.open("POST", "<SERVICEADDRESS>", true);
req.onreadystatechange = MatchSearchComplete; //This is the callback method
//Set up the post headers
req.setRequestHeader("Host", "localhost");
req.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
var params = addressToCheck;
req.setRequestHeader("Content-Length", params.length);
//Iitiate the call to the service
req.send(params); }
}
//The XMLHttpRequest object will fire this method when the
//onreadystatechange event fires...
function MatchSearchComplete()
{
//Check that the response has the correct state and status
//indicating that we've received a response from the server.
if (req.readyState == 4 && req.status == 200)
{
//Our call to the service is complete
var result = req.responseText;
if (result == "false")
alert('The address "'+ req.params +'" is not valid.);
}
}
So what you're doing here is setting up an XMLHttpRequest, pushing the data into it and firing it off to a web service.
Your ASP.NET web application will need a web service built in to it that will be doing the validation of the address.
I might also warn: What if there's only a single address and the user doesn't hit the comma? You should move the guts of the CheckInput() method out to it's own method which parses the addresses. The KeyDown method really should only check if the ',' was pushed. This way you can call the web service to check when the textbox loses focus also. I would also worry about modification of existing addresses without the user hitting the comma again. Therefore, I would wonder about this approach. I would consider that once an address is validated you should have a javascript that only allows that address to be deleted, it shouldn't be editable... whatever approach you take, I'm just warning you that there's some issue with just checking them using the entered ',' approach.
You have to do this with Javascript. After the comma is typed, only then you can pass the email back to C# backend for verification.

Categories

Resources