everybody.I am trying to learn how to use XmlHttpRequest object and look for some examples on the net .I have found this code below and made some changes .Then create a table and added single field called "name"with value varchar .Everything seemed ok .But When i exacute that code I have notice that nothing inserted to the database.So I am wondering is that something wrong or missing in this code or any problem with database I have created .I have no idea
<title></title>
<script type="text/javascript">
function XmlHttpObj() {
var xhr = null;
// Tarayıcımızın ActiveXObject desteği olup olmadığını kontrol ediyoruz.
// İnternet Explorer'da gerçekleştirmek için Microsoft.XMLHTTP
try {
xhr = new ActiveXObject("MsXml2.XMLHTTP");
}
catch (e) {
try {
xhr = new ActiveXObject("Microsoft.XMLHTTP");
}
catch (e) {
if (typeof XMLHttpRequest != "undefined") {
xhr = new XMLHttpRequest();
}
}
}
return xhr;
}
var talep = XmlHttpObj();
function Listen() {
if (talep.readyState == 4 && talep.status == 200) {
var sonuc = talep.responseText;
if (sonuc != null) {
alert("Kayıt Eklendi");
}
else {
alert("Hata Meydana Geldi");
}
}
}
//veritabanına ürün ekleme yapacağımız fonksiyon
//onreadystatechange ile durum değişikliği kontrolü yaptık.
function Ekle() {
talep.open("POST", "Webform1.aspx");
talep.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
talep.onreadystatechange = Listen;
talep.send("mail=" + document.all.Text1.value);
}
</script>
</head>
<body>
<form id="form1" runat="server">
<div>
<input id="Text1" type="text" /><br />
<input id="Button1" type="button" value="Ürün Ekle" onclick="Ekle()"/>
And this is aspx.cs file
if (!string.IsNullOrEmpty(Request.Form["mail"]))
{
try
{
//SqlConnection sqlcon = new SqlConnection("server=.\\sqlexpress;database=northwind;trusted_connection=true");
//SqlCommand sqlcmd = new SqlCommand("insert into productss (name) values (#ad)", sqlcon);
//sqlcmd.Parameters.AddWithValue("#ad", Request.Form["mail"]);
//sqlcon.Open();
//sqlcmd.ExecuteNonQuery();
//sqlcon.Close();
}
catch (Exception)
{
throw;
}
}
I strongly recommend that you do not use XmlHttpRequest directly. It has many complexities and it is very difficult to get it to work on all browsers. I would recommend using PageMethods. It can be done using a ScriptManager or, better yet, using jQuery. For a good article about the latter, see this: Using jQuery to directly call ASP.NET AJAX page methods
Related
On click of the button, a javascript function is called that captures the snapshot from the camera and sends it to process. On backed, we get the image and do some process and get the data in an object called "doc". Upto here the system works fine, but the data that I got in "doc" object doesn't seem to be printed on the page.
Here's the button
<input type="button" value="Capture Snapshot" onClick="CaptureSnapshot()">
And here's the javascript
<script language="JavaScript">
function CaptureSnapshot() {
Webcam.snap(function (data) {
// display results in page
document.getElementById('results').innerHTML = '<img src="' + data + '"/>';
// Send image data to the controller to store locally or in database
Webcam.upload(data,
'/Home/UploadFile',
function (code, text) {
Webcam.reset();
//alert('Snapshot/Image captured successfully...');
});
});
}
</script>
And this is the C# method written in the controller
public async Task<IActionResult> UploadFile()
{
var files = HttpContext.Request.Form.Files;
if (files != null && files.Count > 0)
{
foreach (var uploadedFile in files)
{
if (uploadedFile.Length > 0)
{
var fileName = uploadedFile.FileName;
var path = Path.Combine(Directory.GetCurrentDirectory(), "wwwroot", fileName);
HttpContext.Session.SetString("UploadedFile", fileName);
byte[] imageBytes = ConvertToBytes(uploadedFile);
Document doc = ProcessDocumentImage(imageBytes);
ViewData["Document"] = doc;
}
}
}
else
return Content("file not selected");
return View("Index", "Home");
}
If I put a breakpoint on "doc", I get the data but it doesn't go on the page. What I found is that the page is not submitted at all, maybe this is the reason.
Any ideas to solve this?
I have an image box and a Photo Upload control with a Save button. I need to upload an image into the Image Box.
When I click the Upload button, it should show the Image in the Image Box.
When I click the Save button, the path of the uploaded image should be saved in the database.
My issue is the photo gets uploaded, but only after I click the Upload button for the second time.
P.S. I use a Client side function for uploading the photo.
Following are my codes.
CLIENT SIDE FUNCTION FOR UPLOADING THE PHOTO
function ajaxPhotoUpload() {
var FileFolder = $('#hdnPhotoFolder').val();
var fileToUpload = getNameFromPath($('#uplPhoto').val());
var filename = fileToUpload.substr(0, (fileToUpload.lastIndexOf('.')));
alert(filename);
if (checkFileExtension(fileToUpload)) {
var flag = true;
var counter = $('#hdnCountPhotos').val();
if (filename != "" && filename != null && FileFolder != "0") {
//Check duplicate file entry
for (var i = 1; i <= counter; i++) {
var hdnPhotoId = "#hdnPhotoId_" + i;
if ($(hdnPhotoId).length > 0) {
var mFileName = "#Image1_" + i;
if ($(mFileName).html() == filename) {
flag = false;
break;
}
}
}
if (flag == true) {
$("#loading").ajaxStart(function () {
$(this).show();
}).ajaxComplete(function () {
$(this).hide();
return false;
});
$.ajaxFileUpload({
url: 'FileUpload.ashx?id=' + FileFolder + '&Mainfolder=Photos' + '&parentfolder=Student',
secureuri: false,
fileElementId: 'uplPhoto',
dataType: 'json',
success: function (data, status) {
if (typeof (data.error) != 'undefined') {
if (data.error != '') {
alert(data.error);
} else {
$('#hdnFullPhotoPath').val(data.upfile);
$('#uplPhoto').val("");
$('#<%= lblPhotoName.ClientID%>').text('Photo uploaded successfully')
}
}
},
error: function (data, status, e) {
alert(e);
}
});
}
else {
alert('The photo ' + filename + ' already exists');
return false;
}
}
}
else {
alert('You can upload only jpg,jpeg,pdf,doc,docx,txt,zip,rar extensions files.');
}
return false;
}
PHOTO UPLOAD CONTROL WITH SAVE BUTTON AND IMAGE BOX
<table>
<tr>
<td>
<asp:Image ID="Image1" runat="server" Height="100px" Width="100px" ClientIDMode="Static" />
<asp:FileUpload ID="uplPhoto" runat="server" ClientIDMode="Static"/>
<asp:Label ID="lblPhotoName" runat="server" Text="" ForeColor ="Green" ClientIDMode="Static"></asp:Label>
<asp:Button id="btnSave" runat="server" Text="Upload Photograph" onClick="btnSave_Click" OnClientClick="return ajaxPhotoUpload();"/>
</td>
</tr>
</table>
SAVE BUTTON CLICK EVENT IN SERVER SIDE (to show the uploaded image in the image box)
Protected Sub btnSave_Click(sender As Object, e As EventArgs)
Image1.ImageUrl = hdnFullPhotoPath.Value
End Sub
I’d recommend that you drop client side AJAX upload via JS and stick to standard way of uploading. You can probably achieve the same effects without the excessive javascript.
If file type filtering is an issue you can check this post for more details.
Getting extension of the file in FileUpload Control
In either way you have to make a postback so it doesn’t really matter if you upload from JS or the server side except that second method is less complex.
Adding update panel will make this more user friendly and you should be all done.
<head runat="server">
<title>Index</title>
<script src="../../Scripts/jquery-1.5.1.min.js" type="text/javascript"></script>
<script src="../../Scripts/ajaxupload.js" type="text/javascript"></script>
</head>
<body>
<div>
<input type="button" id="uploadFile" value="Upload File" />(jpg|jpeg|png|gif)
<div id="uploadStatus" style="color: Red">
</div>
</div>
<script type="text/javascript" language="javascript">
new AjaxUpload('#uploadFile', {
action: 'Handler1.ashx',
name: 'upload',
onComplete: function (file, response) {
if (response == '0') {
$('#uploadStatus').html("File can not be upload.");
}
else {
$('#img').attr("src", "response.path");
}
},
onSubmit: function (file, ext) {
if (!(ext && /^(jpg|jpeg|png|gif)$/i.test(ext))) {
$('#uploadStatus').html("Invalid File Format..");
return false;
}
$('#uploadStatus').html("Uploading...");
}
});
</script>
Then create a handler for uploading image on server
public class Handler1 : IHttpHandler
{
public void ProcessRequest(HttpContext context)
{
string a = "1";
if (context.Request.Files != null && context.Request.Files.Count > 0)
{
if (context.Request.Files[0].ContentLength > 1000)
{
a = "0";
}
}
else
{
a = "0";
}
context.Response.Write(a);
context.Response.End();
}
public bool IsReusable
{
get
{
return false;
}
}
}
All, thanks for your time and help.! The tilde(~) symbol was the issue - the file's path wasn't recognized. So I modified my code to replace it with empty space.
var orgpath = data.upfile;
var photopath = orgpath.replace('~/', '');
$('#<%= ImgFacultyPhoto.ClientID%>').attr('src', photopath);
I currently have the following code:
[HttpPost]
public ActionResult Index(IList<LocalPageModel> postPages,
IEnumerable<HttpPostedFileBase> files)
{
if (ModelState.IsValid)
{
foreach (HttpPostedFileBase file in files)
{
if ((file != null) && (file.ContentLength > 0))
{
var fileName = Path.GetFileName(file.FileName);
var path = Path.Combine(Server.MapPath("~/App_Data/"),
fileName);
file.SaveAs(path);
}
}
}
else
{
ManagePagesModel mod = new ManagePagesModel
{
PostPages = postPages
};
return View("Index", mod);
}
return RedirectToAction("Index");
}
In my view, I have a JavaScript button which will add a div so that the user can post another page such as:
$("#add-page").click(function () {
$("#page").append('<div id="page"> #Html.TextBoxFor(u => u.PostPages[0].Title) </div>');
});
How do I make it so that when the user clicks on the JavaScript button, the new text will be appended to the page and u.PostPages[x] will be incremented?
If you want to do it all on the client (no AJAX), maybe don't use the MVC helpers at all, and do it manually instead - you know the HTML that will be rendered, so just do that:
var i = 0;
$("#add-page").click(function () {
$("#page").append('<input type="text" name="PostPages[' + (i++) + '].Title">');
});
Maybe clean the code up a bit so the quotes don't get too confusing, but you get the idea...
You didn't past your view, but I assume you have the following at the top:
#model = ManagePagesModel
If that's the case, you can then use the following #foreach to loop through the page models:
$("#add-page).click(function() {
#foreach(var pageModel in Model.PostPages){
$("#page").append('<div id="page"> #Html.TextBoxFor(u => pageModel.Title) </div>');
});
To increment u.PostPages[x] you may use following code:
<script>
var i = 0;
$("#add-page").click(function () {
i++
$("#page").append('<div id="page"> #Html.TextBoxFor(u => u.PostPages['+i+'].Title') </div>');
});
</script>
Here is small working example: jsfiddle
first of all apologies for my english.
I'm a newby in json area.
My problem is that i can't parse the data recived in a json response into a asp:LinkButton or whatever asp:element, coz i can't create a correct sintax.
Especifically, What I'm trying to do, is this:
<script type="text/javascript">
$.getJSON("http://www.carqueryapi.com/api/0.3/?callback=?", { cmd: "getMakes", min_year:"1941", max_year:"2012"}, function (data) {
var makes = data.Makes;
for (var i = 0; i < makes.length; i++) {
($("<asp:LinkButton ID=\"lb" + i +"\" runat=\"server\" />").text(makes[i].make_display )).appendTo("#lbProva");
}
});
<script>
<ul id="lbProva" class="lb_prova" >
</ul>
I hope that someone could help me coz i've tryed many possibilities but no one was the right one.
Thank u in advance.
You can't create asp.net server controls in javascript on client side. If you want to use json data on client side, you must apply it to already generated html controls.
Actually, you can create server controls only on a server. So the question is how to pass AJAX call response to server and enforce it to refresh desired area on a page.
First variant
<script type="text/javascript">
$(function () {
$.getJSON("http://www.carqueryapi.com/api/0.3/?callback=?", { cmd: "getMakes", year: "2009" },
function (data) {
//The 'data' variable contains all response data.
var makes = $.map(data.Makes, function (make) { return make.make_display; }).join(";");
document.getElementById("<%= CarMakersHiddenField.ClientID %>").value = makes;
__doPostBack("<%= CarMakersUpdatePanel.ClientID %>", "");
});
});
</script>
<asp:UpdatePanel runat="server" ID="CarMakersUpdatePanel" UpdateMode="Conditional">
<ContentTemplate>
<asp:HiddenField runat="server" ID="CarMakersHiddenField" />
<asp:BulletedList runat="server" ID="MakersList" DisplayMode="LinkButton">
</asp:BulletedList>
</ContentTemplate>
</asp:UpdatePanel>
Server code:
protected void Page_Load(object sender, EventArgs e)
{
MakersList.Items.Clear();
foreach (var maker in CarMakersHiddenField.Value.Split(';'))
{
MakersList.Items.Add(maker);
}
}
Second approach is more siutable if you need to pass to server some complex object like array of makers objects. In that case you can serialize this object to JSON string on client and deserialize it on server. Looks like previous version with bit changes:
<script type="text/javascript">
$(function () {
$.getJSON("http://www.carqueryapi.com/api/0.3/?callback=?", { cmd: "getMakes", year: "2009" },
function (data) {
//The 'data' variable contains all response data.
var serializedString = Sys.Serialization.JavaScriptSerializer.serialize(data.Makes);
document.getElementById("<%= CarMakersHiddenField.ClientID %>").value = serializedString;
__doPostBack("<%= CarMakersUpdatePanel.ClientID %>", "");
});
});
</script>
Markup left the same as in the first version.
Server code:
[Serializable]
public class Make
{
public string make_id;
public string make_display;
public bool make_is_common;
public string make_country;
}
protected void Page_Load(object sender, EventArgs e)
{
MakersList.Items.Clear();
if (!String.IsNullOrEmpty(CarMakersHiddenField.Value))
{
var serializer = new DataContractJsonSerializer(typeof(Make[]));
using (var stream = new MemoryStream(Encoding.Unicode.GetBytes(CarMakersHiddenField.Value)))
{
var makes = serializer.ReadObject(stream) as Make[];
if (makes != null)
{
foreach (var maker in makes)
{
MakersList.Items.Add(new ListItem(maker.make_display, maker.make_id));
}
}
}
}
}
How can I execute some javascript when a Required Field Validator attached to a textbox fails client-side validation? What I am trying to do is change the css class of the textbox, to make the textbox's border show red.
I am using webforms and I do have the jquery library available to me.
Here is quick and dirty thing (but it works!)
<form id="form1" runat="server">
<asp:TextBox ID="txtOne" runat="server" />
<asp:RequiredFieldValidator ID="rfv" runat="server"
ControlToValidate="txtOne" Text="SomeText 1" />
<asp:TextBox ID="txtTwo" runat="server" />
<asp:RequiredFieldValidator ID="rfv2" runat="server"
ControlToValidate="txtTwo" Text="SomeText 2" />
<asp:Button ID="btnOne" runat="server" OnClientClick="return BtnClick();"
Text="Click" CausesValidation="true" />
</form>
<script type="text/javascript">
function BtnClick() {
//var v1 = "#<%= rfv.ClientID %>";
//var v2 = "#<%= rfv2.ClientID %>";
var val = Page_ClientValidate();
if (!val) {
var i = 0;
for (; i < Page_Validators.length; i++) {
if (!Page_Validators[i].isvalid) {
$("#" + Page_Validators[i].controltovalidate)
.css("background-color", "red");
}
}
}
return val;
}
</script>
You could use the following script:
<script>
$(function(){
if (typeof ValidatorUpdateDisplay != 'undefined') {
var originalValidatorUpdateDisplay = ValidatorUpdateDisplay;
ValidatorUpdateDisplay = function (val) {
if (!val.isvalid) {
$("#" + val.controltovalidate).css("border", "2px solid red");
}
originalValidatorUpdateDisplay(val);
}
}
});
</script>
This code decorates the original ValidatorUpdateDisplay function responsible for updating the display of your validators, updating the controltovalidate as necessary.
Hope this helps,
I think you would want to use a Custom Validator and then use the ClientValidationFunction... Unless it helpfully adds a css class upon fail.
Some time ago I spend a few hours on it and since then I have been using some custom js magic to accomplish this.
In fact is quite simple and in the way that ASP.NET validation works. The basic idea is add a css class to attach a javascript event on each control you want quick visual feedback.
<script type="text/javascript" language="javascript">
/* Color ASP NET validation */
function validateColor(obj) {
var valid = obj.Validators;
var isValid = true;
for (i in valid)
if (!valid[i].isvalid)
isValid = false;
if (!isValid)
$(obj).addClass('novalid', 1000);
else
$(obj).removeClass('novalid', 1000);
}
$(document).ready(function() {
$(".validateColor").change(function() {validateColor(this);});
});
</script>
For instance, that will be the code to add on an ASP.Net textbox control. Yes, you can put as many as you want and it will only imply add a CssClass value.
<asp:TextBox ID="txtBxEmail" runat="server" CssClass="validateColor" />
What it does is trigger ASP.Net client side validation when there is a change on working control and apply a css class if it's not valid. So to customize visualization you can rely on css.
.novalid {
border: 2px solid #D00000;
}
It's not perfect but almost :) and at least your code won't suffer from extra stuff. And
the best, works with all kind of Asp.Net validators, event custom ones.
I haven't seen something like this googling so I wan't to share my trick with you. Hope it helps.
extra stuff on server side:
After some time using this I also add this ".novalid" css class from code behind when need some particular validation on things that perhaps could be only checked on server side this way:
Page.Validate();
if (!requiredFecha.IsValid || !CustomValidateFecha.IsValid)
txtFecha.CssClass = "validateColor novalid";
else
txtFecha.CssClass = "validateColor";
Here is my solution.
Advantages over other solutions:
Integrates seamlessly with ASP.NET - NO changes required to code. Just call the method on page load in a master page.
Automatically changes the CSS class when the text box or control changes
Disadvantages:
Uses some internal features of ASP.NET JavaScript code
Tested only on ASP.NET 4.0
HOW TO USE:
Requires JQuery
Call the "Validation_Load" function when the page loads
Declare a "control_validation_error" CSS class
function Validation_Load() {
if (typeof (Page_Validators) != "object") {
return;
}
for (var i = 0; i < Page_Validators.length; i++) {
var val = Page_Validators[i];
var control = $("#" + val.controltovalidate);
if (control.length > 0) {
var tagName = control[0].tagName;
if (tagName != "INPUT" && tagName != "TEXTAREA" && tagName != "SELECT") {
// Validate sub controls
}
else {
// Validate the control
control.change(function () {
var validators = this.Validators;
if (typeof (validators) == "object") {
var isvalid = true;
for (var k = 0; k < validators.length; k++) {
var val = validators[k];
if (val.isvalid != true) {
isvalid = false;
break;
}
}
if (isvalid == true) {
// Clear the error
$(this).removeClass("control_validation_error");
}
else {
// Show the error
$(this).addClass("control_validation_error");
}
}
});
}
}
}
}
Alternatively, just iterate through the page controls as follows: (needs a using System.Collections.Generic reference)
const string CSSCLASS = " error";
protected static Control FindControlIterative(Control root, string id)
{
Control ctl = root;
LinkedList<Control> ctls = new LinkedList<Control>();
while ( ctl != null )
{
if ( ctl.ID == id ) return ctl;
foreach ( Control child in ctl.Controls )
{
if ( child.ID == id ) return child;
if ( child.HasControls() ) ctls.AddLast(child);
}
ctl = ctls.First.Value;
ctls.Remove(ctl);
}
return null;
}
protected void Page_PreRender(object sender, EventArgs e)
{
//Add css classes to invalid items
if ( Page.IsPostBack && !Page.IsValid )
{
foreach ( BaseValidator item in Page.Validators )
{
var ctrltoVal = (WebControl)FindControlIterative(Page.Form, item.ControlToValidate);
if ( !item.IsValid ) ctrltoVal.CssClass += " N";
else ctrltoVal.CssClass.Replace(" N", "");
}
}
}
Should work for most cases, and means you dont have to update it when you add validators. Ive added this code into a cstom Pageclass so it runs site wide on any page I have added validators to.