The Form:
<form action="upload-document.aspx" onsubmit="sendAndClose();" method="post" enctype="multipart/form-data">
<input name="fileToUpload" id="fileToUpload" type="file" />
<input type="submit" name="submit" value="Send" />
</form>
The AJAX:
function sendAndClose() {
currentUrl = location.protocol + '//' + location.host + location.pathname;
var data = new FormData();
var file = $("#fileToUpload")[0].files[0];
data.append("name", file.name);
data.append("size", file.size);
data.append("type", file.type);
data.append("file", file);
$.ajax({
type: "POST",
url: currentUrl + '/Persist',
dataType: 'json',
data: data,
cache: false,
contentType: false,
processData: false,
success: function () {
parent.$.fancybox.close();
},
error: function (request, error) {
alert("[" + error + "] - FAIL: " + request.responseText);
parent.$.fancybox.close();
}
});
}
The Code-Behind:
[WebMethod]
public static bool Persist(object data)
{
return true;
}
when the form is submitted, it runs the ajax and goes straight to the error callback before entering the webmethod. can anybody tell me why?
also, after the 'var file' I had an alert to show the files name, size, etc... so it gets the file, the problem is that ajax is refusing to comunicate with the code-behind.
I had a similar problem that was solved by adding this parameter in the ajax function :
traditional: true
So try this code for your AJAX call :
$.ajax({
type: "POST",
url: currentUrl + '/Persist',
dataType: 'json',
data: data,
cache: false,
contentType: false,
processData: false,
traditional: true,
success: function () {
parent.$.fancybox.close();
},
error: function (request, error) {
alert("[" + error + "] - FAIL: " + request.responseText);
parent.$.fancybox.close();
}
});
You cannot invoke a webmethod like http://localhost:40899/upload-document.aspx/Persist. The currentUrl is incorrect.
Following on from my question in the comments section I would add that your public static bool Persist... method MUST be in the page (ASPX) and not a user-control (ASCX).
This is because the page (ASPX) is "visible" to the outside world via a URL whereas a user-control (ASCX) is only used on the server to build up the page not a URI in its own right, and therefore not accessible to external callers.
If you need to call the method in the user-control you will need to move your Persist method (with WebMethod attribute) to your page (ASPX) and then make a call from that method into your user-control (ASCX).
Related
I want to post data in the Mssql Database using Asp.netCore Api and Html Form. I have Added This script to post data.but All the values are coming null
Jquery script in Html File
<script type="text/javascript">
var valdata = $("#formData").serialize();
$(document).ready(function () {
$("#btnsubmit").click(function (e) {
let formData = {};
$("#formData").serializeArray().map((x) => { formData[x.name] = x.value; });
$.ajax({
url: "https://localhost:44389/Register",
contentType: "application/json; charset=utf-8",
type: 'POST',
dataType: 'json',
data: valdata,
success: function (data) {
alert(data);
},
failure: function (data) {
alert("Failure: " + data);
},
error: function (data) {
alert("Error: " + data);
}
});
});
});
</script>
.net Core Api
[HttpPost]
[Route("Register")]
public void RegisterExecute([FromBody]CustmRegistration Register)
{
try
{
userInterface.InsertCustomer(Register);
}
catch (Exception ex)
{
throw new Exception(ex.Message);
}
}
but All the values are coming null
Where are these values null? my suggestion is to start debugging a bit more thoroughly.
Have you tried your api function trough postman or a tool likewise?
Settting breakpoints can be nice to look into your program's data at runtime.
if these values are null in your database it would be nice to see what userInterface.InsertCustomer(Register); does.
Once you know if your .net part is working start debugging your ajaxc call. take a look at the network section of the developer tools form the browser you are using.
If you have collected more data, people can help you more easelly.
1.When you use .serialize(), it generates the data in a query string format which needs to be sent using the default contentType which is application/x-www-form-urlencoded; charset=UTF-8, not as JSON. Either remove the contentType option or specify contentType: application/x-www-form-urlencoded; charset=UTF-8 can work.
2.Also you need move the serialize method into onclick event.
3.Be sure change [FromBody] to [FromForm].
Here is a whole working demo:
View:
#model CustmRegistration
<form id="formData">
<!--more code-->
<input type="button" id="btnsubmit"value="create" />
</form>
#section Scripts
{
<script type="text/javascript">
$(document).ready(function () {
$("#btnsubmit").click(function (e) {
var valdata = $("#formData").serialize(); //move to here...
$.ajax({
url: "/home/Register",
//contentType: "application/json; charset=utf-8",
type: 'POST',
dataType: 'json',
data: valdata,
success: function (data) {
alert(data);
},
failure: function (data) {
alert("Failure: " + data);
},
error: function (data) {
alert("Error: " + data);
}
});
});
});
</script>
}
Controller:
[HttpPost]
[Route("Register")]
public void RegisterExecute([FromForm]CustmRegistration Register)
{ //...}
There is a div on my page currently that makes a lot of requests to the server, so the pages takes about 10 seconds to load. We don't always need this data, so I want to be able to have the page load with all of the info except for this one div. Once the page is loaded 100% I want it to load this div (maybe show a loading...).
I've made an ajax request from my TrackingData.aspx as a test, but I can't seem to get this to work.
My JavaScript
function ShowCurrentTime() {
$.ajax({
type: "POST",
url: "TrackingData.aspx/GetCurrentTime",
data: '{name: "' + $("#<%=txtUserName.ClientID%>")[0].value + '" }',
contentType: "application/json; charset=utf-8",
dataType: "json",
success: OnSuccess,
failure: function(response) {
alert("bye");
}
});
}
function OnSuccess() {
alert("hi");
}
And the HTML
Your Name :
<asp:TextBox ID="txtUserName" runat="server"></asp:TextBox>
<input id="btnGetTime" type="button" value="Show Current Time"
onclick = "ShowCurrentTime()" />
</div>
The C# code is simply
public static string GetCurrentTime(string name)
{
return "Hello " + name + Environment.NewLine + "The Current Time is: "
+ DateTime.Now.ToString();
}
There is a TrackingData.aspx in the same folder, and it has a method GetCurrentTime. This is just a test method, but I should be able to do the rest on my own once I get this working.
You need to add this before your static method (GetCurrentTime):
[System.Web.Services.WebMethod]
And to avoid some faults you can use json stringify for your data:
data: { name: JSON.stringify($("#<%=txtUserName.ClientID%>")[0].value)}
I wanted to apply bootstrap button to dynamically create buttons via Ajax Call.In my code without bootstrap css class it's working on just default buttons But i want to apply bootstrap button When i use bootstrap css class --> class=btn btn-large btn-primary,Then it's not working
My Code
function LoadSpecialFilesToUser() {
debugger;
var newurls = '<%= ResolveUrl("/WebMethods.aspx/GetSpecialFilesToUsers") %>';
$.ajax({
url: newurls,
type: "POST",
data: JSON.stringify({ Id: "<%=GetUserID()%>" }),
dataType: "json",
contentType: "application/json; charset=utf-8",
success: function (Result) {
$.each(Result.d, function (key, value) {
$("#SpecialFiles").append("<button class=btn btn-large btn-primary><a href=" + value.FilePath + "/>" + value.Caption + "</button>");//<-- In here without class=btn btn-large btn-primary.It's working
});
},
error: function (e, x) {
alert(x.ResponseText);
}
});
}
I'm trying to do something, Can we call User control code behind method using Jquery ajax ?
likes:
ASCX CODE:
<script type="text/javascript">
function ShowCurrentTime() {
$.ajax({
type: "POST",
url: "Uploads.aspx/GetCurrentTime",
data: '{name: "' + $("#<%=txtUserName.ClientID%>")[0].value + '" }',
contentType: "application/json; charset=utf-8",
dataType: "json",
success: OnSuccess,
failure: function (response) {
alert(response.d);
}
});
}
function OnSuccess(response) {
alert(response.d);
}
ASCX.CS
[System.Web.Services.WebMethod]
public static string GetCurrentTime(string name)
{
return "Hello " + name + Environment.NewLine + "The Current Time is: "
+ DateTime.Now.ToString();
}
But its will create an error please can any one what do i am wrong.
The user control doesn't have all the functionality of a page and can't be called directly.Check out the following link for complete solution
Creating a Page method (ScriptMethod) within an ASCX user control using AJAX, JSON, base classes and reflection
I have a dialog in an ASP.Net,c# application.This dialog has a textbox.When I choose save I want to call a function from C# who makes some verifications in the database and then to get the result in javascript/jquery.If the inserted value is true I want to close the dialog other way to remain opened,but I can't succed to close the dialog box after i receive true from c# function.Below is the code:
ascx :
<div id="popup" title="Choose Delegate">
<label>Delegate<label><input type="textbox" value="" name="inputD" id=="inputD"/>
</div>
Javascript:
$('#btnAdd').click(function(e){
$('#divPopup').slow("show");
$('#divPopup').dialog({
height:150,
width:300,
modal:true,
buttons:{
"close":function(){$(this).dialog("close");}
"save":function(){
var obj=document.getElementid("inputD");
$.ajax({
type: "POST",
url: "add.aspx/check",
data: "{delegate: '" + obj.Value+"'}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (msg) {
rez= "OK";
$(this).dialog("close");
},
failure: function () {alert("FAIL"); }}); }
});
}
C#:
[WebMethode]
public static Boolean check(string delegate)
{
.....
return true;
}
C# methode returns corect value.
I try also this :
$('#btnAdd').click(function(e){
$('#divPopup').slow("show");
$('#divPopup').dialog({
height:150,
width:300,
modal:true,
buttons:{
"close":function(){$(this).dialog("close");}
"save":function(){
var obj=document.getElementid("inputD");
var rez ;
$.ajax({
type: "POST",
url: "add.aspx/check",
data: "{delegate: '" + obj.Value+"'}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (msg) {
rez= "OK";
},
failure: function () {alert("FAIL"); }
});
if (rez="OK")
$(this).dialog("close");
}
});
But it doesn't see the rez value in this case.
Thanks !
You can use an Ajax Call in your "save":function(e) and just check the returned value if true close dialog, else remain opened
Ajax calls are really simple to implement, I let you search that :)
You need a web-service on the server side. (preferably REST)
http://restsharp.org/ is an easy to use library for that.
Take a look at this question for more info.
In the front end you make an ajax call to you're REST api (I see you use jquery so it won't be that hard ;))