mam TextBox
z AutoCompleteExtender
gdy osoba zaczyna wpisywać na Listę TextBox
z nazwą miasta Pojawiają .To działa dobrze, ale teraz chcę, aby potwierdzić, że jeśli po prostu wpisać textbox
i nie wybrać jeden z listy potwierdzającej, że miasto nie istnieje w bazie danych. Chcę sprawdzić to za pomocą Ajax i bez PostBack
Przed ostatecznym przesłaniem form
.Validation z ajax AutoCompleteExtender
6
A
Odpowiedz
1
Dodaj nowy plik js z zawartością poniżej i dodaj dodać odniesienie na nim ToolkitScriptManager za Scrips
kolekcji:
Type.registerNamespace('Sjax');
Sjax.XMLHttpSyncExecutor = function() {
Sjax.XMLHttpSyncExecutor.initializeBase(this);
this._started = false;
this._responseAvailable = false;
this._onReceiveHandler = null;
this._xmlHttpRequest = null;
this.get_aborted = function() {
//Parameter validation code removed here...
return false;
}
this.get_responseAvailable = function() {
//Parameter validation code removed here...
return this._responseAvailable;
}
this.get_responseData = function() {
//Parameter validation code removed here...
return this._xmlHttpRequest.responseText;
}
this.get_started = function() {
//Parameter validation code removed here...
return this._started;
}
this.get_statusCode = function() {
//Parameter validation code removed here...
return this._xmlHttpRequest.status;
}
this.get_statusText = function() {
//Parameter validation code removed here...
return this._xmlHttpRequest.statusText;
}
this.get_xml = function() {
//Code removed
}
this.executeRequest = function() {
//Parameter validation code removed here...
var webRequest = this.get_webRequest();
if (webRequest === null) {
throw Error.invalidOperation(Sys.Res.nullWebRequest);
}
var body = webRequest.get_body();
var headers = webRequest.get_headers();
var verb = webRequest.get_httpVerb();
var xmlHttpRequest = new XMLHttpRequest();
this._onReceiveHandler = Function.createCallback(this._onReadyStateChange, { sender: this });
this._started = true;
xmlHttpRequest.onreadystatechange = this._onReceiveHandler;
xmlHttpRequest.open(verb, webRequest.getResolvedUrl(), false); // False to call Synchronously
if (headers) {
for (var header in headers) {
var val = headers[header];
if (typeof (val) !== "function") {
xmlHttpRequest.setRequestHeader(header, val);
}
}
}
if (verb.toLowerCase() === "post") {
if ((headers === null) || !headers['Content-Type']) {
xmlHttpRequest.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
}
if (!body) {
body = '';
}
}
this._started = true;
this._xmlHttpRequest = xmlHttpRequest;
xmlHttpRequest.send(body);
}
this.getAllResponseHeaders = function() {
//Parameter validation code removed here...
return this._xmlHttpRequest.getAllResponseHeaders();
}
this.getResponseHeader = function (header) {
//Parameter validation code removed here...
return this._xmlHttpRequest.getResponseHeader(header);
}
this._onReadyStateChange = function (e, args) {
var executor = args.sender;
if (executor._xmlHttpRequest && executor._xmlHttpRequest.readyState === 4) {
//Validation code removed here...
executor._responseAvailable = true;
executor._xmlHttpRequest.onreadystatechange = Function.emptyMethod;
executor._onReceiveHandler = null;
executor._started = false;
var webRequest = executor.get_webRequest();
webRequest.completed(Sys.EventArgs.Empty);
//Once the completed callback handler has processed the data it needs from the XML HTTP request we can clean up
executor._xmlHttpRequest = null;
}
}
}
Sjax.XMLHttpSyncExecutor.registerClass('Sjax.XMLHttpSyncExecutor', Sys.Net.WebRequestExecutor);
Na stronie:
<ajaxToolkit:ToolkitScriptManager runat="server" ID="ScriptManager1">
<Scripts>
<asp:ScriptReference Path="~/XMLHttpSyncExecutor.js" />
</Scripts>
</ajaxToolkit:ToolkitScriptManager>
Następnie dodać CustomValidator dla docelowej TextBox i funkcji użyć poniżej do sprawdzania klienta:
<asp:TextBox runat="server" ID="myTextBox" Width="300" autocomplete="off" />
<asp:CustomValidator runat="server" ID="myTbCustomValidator" ControlToValidate="myTextBox"
Text="*" Display="Dynamic" ValidateEmptyText="false" ClientValidationFunction="validateTextBox"
OnServerValidate="ValidateTextBox" />
function validateTextBox(sender, args) {
if (args.Value.length > 0) {
var extender = $find("AutoCompleteEx"); // AutoComplete extender's BehaviorID
if (extender._completionListElement) {
var children = extender._completionListElement.childNodes;
var length = extender._completionListElement.childNodes.length;
for (var i = 0; i < length; i++) {
if (children[i].innerHTML == args.Value) {
args.IsValid = true;
return;
}
}
}
var request = new Sys.Net.WebRequest();
request.set_url('<%= ResolveClientUrl("~/AutoComplete/AutoComplete.asmx/Validate") %>');
var body = Sys.Serialization.JavaScriptSerializer.serialize({ value: args.Value });
request.set_body(body);
request.set_httpVerb("POST");
request.get_headers()["Content-Type"] = "application/json; encoding=utf-8";
request.add_completed(function (eventArgs) {
var result = Sys.Serialization.JavaScriptSerializer.deserialize(eventArgs.get_responseData());
args.IsValid = result.d;
});
var executor = new Sjax.XMLHttpSyncExecutor();
request.set_executor(executor);
request.invoke();
}
}
Główną ideą powyższego kodu jest najpierw sprawdzenie sugerowanych pozycji dla wprowadzonego tekstu, a jeśli nie ma żadnej pewności, to wykonanie synchronicznego wywołania AJAX do metody Validate usługi internetowej lub metody strony. Ta metoda powinna mieć taki podpis: public bool Validate(string value)
P.S. Kod XMLHttpSyncExecutor podany tutaj: Using Synchronous ASP.Net AJAX Web Service Calls and Scriptaculous to Test your JavaScript
Powiązane problemy
- 1. AJAX Rails Validation
- 2. Yii - Używanie Ajax Validation
- 3. Wykryj zdarzenie select AutoCompleteExtender
- 4. ASP.NET MVC Validation Framework podczas publikowania za pośrednictwem jquery $ .ajax?
- 5. Skonfiguruj NancyFx z Fluent Validation
- 6. AVRO Validation
- 7. AutoCompleteExtender ma niewłaściwą pozycję, dla przeglądarek Webkit po przewinięciu strony
- 8. jQuery Plugin Validation & Form
- 9. Django Javascript validation Form
- 10. Bean Validation API
- 11. Wyzwalanie jQuery Validation ręcznie?
- 12. Entity Framework Validation & usage
- 13. Entity Framework Validation
- 14. ASP.net MVC Validation Hook
- 15. problemem Validation z JSP i Eclipse
- 16. Metoda niestandardowa z wtyczką jQuery Validation
- 17. Angular JS Email Validation z kodami Unicode
- 18. Validation nie pracuje z INTL-TEL-Input
- 19. Laravel File Upload Validation
- 20. Jak ponownie zainicjować jQuery unobstrusive validation?
- 21. C# - TextBox Validation
- 22. Laravel5: Middleware or Validation?
- 23. JQuery Validation Internationalization Problem
- 24. laravel Password & Password_Confirmation Validation
- 25. Codeigniter: dropdown validation set_rules
- 26. jQuery validation onblur
- 27. Uri validation pack
- 28. Rails Dynamic Validation
- 29. GWT DateBox validation
- 30. Validation adnotacji i własność plik