I am having a drop down with "Create New" option. If User clicks "Create New" option then Popup window will display with Save button. In that Popup window, User will enter data and after User will save this data on server. To achieve this what approach I should follow. Any Help Please..??
use for example from javascript:
$(function () {
$("#btnSave").click(function () {
var person = { Name: 'MrX', Age: 25 };
$.ajax({
type: "POST",
url: "/AddUser",
data: car,
datatype: "html",
success: function (data) {
/*
done
*/
}
});
});
});
and then into your controller:
[HttpPost]
public JsonResult AddUser(string data)
{
/* deserilize and insert */
or if you are using web forms you need to decorate your method like:
[WebMethod]
public static void AddUser(string data)
{
/* deserialize, add */
Note: out there are so many options you can do this. it depends in what conditions you are or what you like
JavaScript function to call C# Web Method from Ajax.
<script>
function savefile()
{
var person = 'test',
returnEmail = 'test#test.com';
var dataValue = { "name": person, "returnAddress": returnEmail };
var url = "WebForm1.aspx/OnSubmit";
$.ajax({
type: "POST",
url: url,
data: JSON.stringify(dataValue),
contentType: 'application/json; charset=utf-8',
dataType: 'json',
success: function(msg) {
if (msg.d != null) {
alert("We returned: " + msg.d);
}
},
error: function(XMLHttpRequest, textStatus, errorThrown) {
alert("Request: " + XMLHttpRequest.toString() + "\n\nStatus: " + textStatus + "\n\nError: " + errorThrown);
}
});
};
</script>
<asp:Button ID="Button1" runat="server" Text="Button" OnClientClick="savefile()" />
Web Method to receive Ajax Request and Process it.
using System.Web.Services;
[WebMethod]
public static string OnSubmit(string name, string returnAddress)
{
return "it worked";
//Code for writing your data to text file.
}
Related
I can't access webmethod within javascript. It gives the error in the title. Why might it be caused?
Js :
function funcGoster() {
$.ajax({
type: "POST",
url: "/WebService1.asmx/HelloWorld",
data: "{}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (msg) {
// document.getElementById('text').innerHTML =
},
error: function (e) {
alert("başarısız" + e);
}
});
}
</script>
WebMethod :
public class WebService1 : System.Web.Services.WebService
{
[WebMethod]
public static string HelloWorld()
{
return "Hello World";
}
}
Ok, what you have looks quite good, but note in the web service page, you have to un-comment the one line.
so, you should have this:
{
[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[System.ComponentModel.ToolboxItem(false)]
// To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line.
[System.Web.Script.Services.ScriptService]
public class WebService1 : System.Web.Services.WebService
{
[WebMethod]
public string HelloWorld()
{
return "Hello World";
}
}
}
Ok, now our code and markup:
<asp:Button ID="Button1" runat="server" Text="Button" Width="153px"
OnClientClick="ajtest();return false;"/>
<br />
</div>
<script>
function ajtest() {
$.ajax({
type: "POST",
url: "/WebService1.asmx/HelloWorld",
data: "{}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (msg) {
alert(' back from ajax message = ' + msg.d)
},
error: function (xhr, status, error) {
var errorMessage = xhr.status + ': ' + xhr.statusText
alert('Error - ' + errorMessage)
}
});
}
</script>
So, we also assume you have jQuery setup for this page? You need that.
You can call the web method without jQuery.
So, pure JavaScript, you could use this:
// Web method call without jQuery
function ajtest2() {
// ajax call without jquery
var xhr = new XMLHttpRequest()
xhr.open('POST', '/WebService1.asmx/HelloWorld')
xhr.setRequestHeader('Content-Type', 'application/json')
xhr.send('{}');
xhr.onload = function () {
if (xhr.status === 200) {
var userInfo = JSON.parse(xhr.responseText)
alert(' back form ajaxes message = ' + userInfo.d)
}
}
}
I am making a email contact form with a ajax post on a umbraco site, I am halway thru it and was just testing the ajax part and I get a "Web Service method name is not valid" error when it runs.
I have a booking.cs in app_code, then booking.asmx in a webservice folder,
[WebService(Namespace = "http://localhost/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[System.Web.Script.Services.ScriptService]
public class Booking : System.Web.Services.WebService
{
public string Email { get; set; }
[WebMethod]
[System.Web.Script.Services.ScriptMethod(ResponseFormat = System.Web.Script.Services.ResponseFormat.Json)]
public string SaveIt(string Email)
{
try
{
return "success";
}
catch (Exception er)
{
return "error";
}
}
}
javascript:
$("#email_popup_submit").click(function (e) {
$.ajax({
url: '/webservice/Booking.asmx/SaveIt',
type: 'POST',
contentType: 'application/json; charset=utf-8',
dataType: 'json',
data: { 'Email': 'testemail' },
beforeSend: function () {
},
success: function (data) {
//console.log(data.d);
if (data.d == "success") {
e.preventDefault();
// console.log('SUCCESS!');
} else {
}
},
error: function (jqXhr, textStatus, errorThrown) {
console.log("Error '" + jqXhr.status + "' (textStatus: '" + textStatus + "', errorThrown: '" + errorThrown + "')");
}
});
})
Uncomment following line from your service code to be enabled to call from javascript/ajax
[System.Web.Script.Services.ScriptService]
you could try to change data parameter to this:
data: '{ "Email":"testemail"}'
I have an MVC application where I am uploading picture files in an application.
The code for this:
var files = $(".uploadFile").data("files");
$.each(files, function (key, value) {
data.append('file', value);
})
$('.userForm *').filter(':input').each(function (index, value) {
data.append(value.id, $("#" + value.id).val());
});
$.ajax({
url: "/Customer/AddCustomer",
type: 'POST',
data: data,
cache: false,
processData: false,
contentType: false,
success: function (data) {
// logic
$.LoadingOverlay("hide");
},
error: function (event, jqxhr, settings, thrownError) {
// logic
$.LoadingOverlay("hide");
}
});
Server code:
public string AddCustomer(HttpPostedFileBase file, Customer customer)
{
// add customer and return to edit view
return partialView("customerEdit");
}
I am trying to figure out how i can add a property to each file that I send?
for example for every file that i add I create a list which I append to the DOM.
In this list there is a checkbox next to each file which indicates if this file(picture) should be the profile picture or not.
How do I append a boelan property to each file?
Thanks to #adeneo my brain got a jump start.
I had to retrhink my strategy here since I did not want to send the extra paramaters as a concatinated string.
I did the following:
In my first post I sent the file and the customer data. I saved the customer in the DB and for the file i stored it in tempdata in order to be able to access it in my second post where i would be savinng the file to the db with desiered extra paramaters.
script:
$.ajax({
url: "/Customer/AddCustomer",
type: 'POST',
data: data,
cache: false,
processData: false,
contentType: false,
success: function (data) {
// "Pictures" is an array that contains objects with all the file names and other properties.
$.ajax({
url: "/Customer/AddCustomerPictures",
type: 'POST',
data: JSON.stringify({ pictureFiles: Pictures}),
contentType: 'application/json; charset=utf-8',
success: function(data) {
//logic
}
});
//logic
},
error: function (event, jqxhr, settings, thrownError) {
//logic
}
});
server code, NOTE entire soloution not included:
public ActionResult AddCustomer(CustomerM customer)
{
var Id = _iScissorFingersManager.AddCustomer(customer.FirstName, customer.LastName, customer.Email,customer.PhoenNumber);
if (Request.Files.Count != 0)
{
TempData["files"] = Request.Files;
TempData["Id"] = Id;
}
// add customer and return to edit view
return PartialView("CustomerEdit", customer);
}
public ActionResult AddCustomerPictures(List<PictureFiles> pictureFiles)
{
var files = (HttpFileCollectionBase)TempData["files"];
var id = (long) TempData["Id"];
if (files != null)
{
foreach (var p in pictureFiles)
{
for (int i = 0; i < files.Count; i++)
{
HttpPostedFileBase hpf = files[i];
p.Name == files[i].FileName && p.IsProfile ? _iScissorFingersManager.UploadCustomerPictures(hpf.InputStream, hpf.ContentType, id, true), _iScissorFingersManager.UploadCustomerPictures(hpf.InputStream, hpf.ContentType, id);
}
}
}
return PartialView("CustomerProfileImage");
}
I am now trying to build a dnn module using ajax calls. But there is a jquery error stating
SyntaxError: Unexpected token <
I have tried to work around with ajax "url: " and tried to create a new ascx at the root folder but still showing error 404.
My ajax call is as below
$.ajax({
url: "NewsManagement.ascx/Add",
contentType: "application/json; charset=utf-8",
dataType: "json",
method: "POST",
beforeSend: function () {
},
cache: false,
data: {
title : $('#txt_Title').val(),
news_content : $('#txt_Content').val(),
image : $('#file_Image').val(),
chapter_id : $('#sel_Chapter').val(),
is_draft : $('#chk_Draft').val(),
posted_date : $('#dp_PostDate').val(),
created_by : "",
lastupdate_by : ""
},
success: function (data) {
console.log(data);
if (data == "success") {
console.log(data);
}
else {
initMdlError("SERVER : " + data);
}
},
error: function (data, textStatus, error) {
// ERROR IS BEING CALLED FROM HERE
console.log("JQUERY JAVASCRIPT : " + error);
initMdlError(error);
},
complete: function () {
console.log('complete');
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
Is there any way to solve the issues?
The problem you're running into is that DNN isn't handling the requested URL properly that you are calling. If you want to call a service URL in DNN you're going to want to setup routes to handle the calls.
namespace Christoc.Com.Modules.SlidePresentation.services
{
public class SlidePresentationRouteMapper : IServiceRouteMapper
{
public void RegisterRoutes(IMapRoute mapRouteManager)
{
mapRouteManager.MapRoute("SlidePresentation", "{controller}.ashx/{action}",
new[] {"Christoc.Com.Modules.SlidePresentation.services"});
}
}
}
In the Controller you can define the methods available
[DnnAuthorize(AllowAnonymous = true)]
public ActionResult ListOfSlides()
{
try
{
var slides = Slide.GetSlides(ActiveModule.TabID, ActiveModule.ModuleID);
return Json(slides, JsonRequestBehavior.AllowGet);
}
catch (Exception exc)
{
DnnLog.Error(exc);
return Json(null, JsonRequestBehavior.AllowGet);
}
}
https://slidepresentation.codeplex.com/SourceControl/latest#DesktopModules/SlidePresentation/services/SlidePresentationController.cs
sample Javascript
//get slides on initialization
this.init = function(element) {
//var data = {}; //removed because we don't need this
//data.moduleId = moduleId; //removed because we don't need this when calling setModuleHeaders
//data.tabId = tabId; //removed because we don't need this
//serviceFramework.getAntiForgeryProperty(); //removed because we don't need this
$.ajax({
type: "POST",
cache: false,
url: baseServicePath + 'ListOfSlides',
//data: data,
//dataType:"json",
beforeSend: serviceFramework.setModuleHeaders
}).done(function(data) {
viewModel.slides = ko.utils.arrayMap(data, function(s) {
return new slide(s);
});
ko.applyBindings(viewModel);
$(element).jmpress();
}).fail(function () {
Console.Log('Sorry failed to load Slides');
});
};
Here's an example module that does this
https://slidepresentation.codeplex.com/
And a user group video I did years ago on this module.
https://www.youtube.com/watch?v=hBqn5TsLUxA
Is this even possible? I have a webform with certain textboxes etc and a file upload element. I am trying to send the data to webmethod using .ajax() method.
It seems to me that it is not possible to send file content to the webmethod in this manner. I am not even able to hit the webmethod.
script type="text/javascript">
var btn;
var span;
$(document).ready(function (e) {
$('#btnsave').on('click', function (event) {
Submit();
event.preventDefault();
});
})
function Submit() {
$.ajax({
type: "POST",
url: "SupplierMst.aspx/RegisterSupplier",
data: "{'file' : " + btoa(document.getElementById("myFile").value) + ",'biddername':" + document.getElementById("txtsuppliername").value + "}",
async: true,
contentType: "application/json; charset=utf-8",
success: function (data, status) {
console.log("CallWM");
alert(data.d);
},
failure: function (data) {
alert(data.d);
},
error: function (data) {
alert(data.d);
}
});
}
</script>
HTML:
<input id="txtsuppliername" type="text" /><br />
<input type="file" id="myFile">
Code behind :
[WebMethod]
public static string RegisterSupplier(string file, string biddername)
{
// break point not hit
return "a";
}
I have been trying to find solution to this for hours now. Nobody seems to be able help me out on this. Is this even possible using this approch. If not how do I do it? Somebody suggested that I should try to submit entire form instead of passing individual values.
This can be done without any library, by using the JavaScript FileReader API. With it, modern browsers can read the content of the file using JavaScript once it has been selected by the user, and then you could proceed as you were doing (encoding it as a string, and sending it over to the server).
The code would be like this (using the one above as a reference):
// NEW CODE
// set up the FileReader and the variable that will hold the file's content
var reader = new FileReader();
var fileContent = "";
// when the file is passed to the FileReader, store its content in a variable
reader.onload = function(e) {
fileContent = reader.result;
// for testing purposes, show content of the file on console
console.log("The file content is: " + fileContent);
}
// Read the content of the file each time that the user selects one
document.getElementById("myFile").addEventListener("change", function(e) {
var selectedFile = document.getElementById('myFile').files[0];
reader.readAsText(selectedFile);
})
// END NEW CODE
var btn;
var span;
$(document).ready(function (e) {
$('#btnsave').on('click', function (event) {
Submit();
event.preventDefault();
});
})
function Submit() {
$.ajax({
type: "POST",
url: "SupplierMst.aspx/RegisterSupplier",
// changed this line too!
data: {
'file': btoa(fileContent),
'biddername': document.getElementById("txtsuppliername").value
},
async: true,
contentType: "application/json; charset=utf-8",
success: function (data, status) {
console.log("CallWM");
alert(data.d);
},
failure: function (data) {
alert(data.d);
},
error: function (data) {
alert(data.d);
}
});
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<input id="txtsuppliername" type="text" /><br />
<input type="file" id="myFile">
You can run the code above, select a file (use a plain text file for testing so it's readable), and check the console to see its content. Then the rest of the code would be the same (I made a slight change to fix the parameters in the AJAX call).
Notice that sending the file like this has limits: if you use the GET method, you'll have a shorter parameter size limit, and with POST it will depend on the server settings... but I guess that you had those limits even for a file.
First of all go to App_Start>>RouteConfig.cs>>settings.AutoRedirectMode = RedirectMode.Off; and then Just Replace your function by my code it will definitely work for you,
Good Luck..
function Submit() {
$.ajax({
type: "POST",
url: "UploadImage.aspx/RegisterSupplier",
data: "{'file' : " + JSON.stringify(document.getElementById("myFile").value) + ",'biddername':" + JSON.stringify(document.getElementById("txtsuppliername").value) + "}",
async: true,
contentType: "application/json; charset=utf-8",
success: function (data, status) {
console.log("CallWM");
alert(data.d);
},
failure: function (data) {
alert(data.d);
},
error: function (data) {
alert(data.d);
}
});