Using Ajax, Jquery inserting data in database in Asp.Net? - asp.net

![enter image description here][1]In asp.net, I am trying to insert data using Ajax, Jquery but I am not getting insert data in database, when I place break point at a method but compiler is not coming at break point. Please help me, I am placing the code.
<script type ="text/javascript" >
$(document).ready(function () {
$('#btns').click(function () {
var firstname = $('#<%= txtFirstname.ClientID %>').val();
var phonenumber = $('#<%= txtphonenumber.ClientID %>').val();
var orgtype = $('#<%= ddlOrgatype.ClientID %>').text();
var orgisaname = $('#<%= txtorganame.ClientID %>').val();
var orgnisemail = $('#<%= txtorgemail.ClientID %>').val();
var stateid = $('#<%= ddlstate.ClientID %>').val();
var districtid = $('#<%= ddlDistrict.ClientID %>').val();
var location = $('#<%= txtlocatio.ClientID %>').val();
var userid = $('#<%= txtusername.ClientID %>').val()
var password = $('#<%= txtpassword.ClientID %>').val();
$.ajax({
type:'POST',
contentType: "application/json; charset=utf-8",
url: "Registrationpage.aspx/InsertData",
data: "{'firstname':'" + firstname + "','phonenumber':'" + phonenumber + "','Organitype':'" + orgtype + "','OrgnaisaName':'" + orgisaname + "','OrgnaisaEmail':'" + orgnisemail + "','Stateid':'" + stateid + "','Districtid':'" + districtid + "','Location':'" + location + "','Userid':'" + userid + "','passowrd':'" + password + "'}",
dataType: "json",
success: function(data) {
alert('Inserted');
$('#dvreslt').html = "Inserted Successfully";
} ,
error: function (data) { alert(Error) }
});
});
});
//////////
[WebMethod]
protected static string InsertData(string firstname, string phonenumber, string Organitype, string OrgnaisaName, string OrgnaisaEmail, string Stateid, string Districtid, string Location, string Userid, string passowrd)
{
IBusinessLogic iBusinessLogic = BLFactory.GetBLObject(BLObjectType.Register);
BusinessService businessService = new BusinessService();
RegisterDO objRegisterDO = new RegisterDO();
objRegisterDO.UserName = firstname; objRegisterDO.MobileNo = phonenumber; objRegisterDO.organisationType = Organitype;
objRegisterDO.OrganisationName = OrgnaisaName; objRegisterDO.OrganisationEmail = OrgnaisaEmail; objRegisterDO.StateID = Convert.ToInt32(Stateid);
objRegisterDO.Distictid = Convert.ToInt32(Districtid); objRegisterDO.Location = Location; objRegisterDO.UserID = Userid; objRegisterDO.Password = passowrd;
businessService.BusinessLogic = iBusinessLogic;
if (businessService.Execute(OperationType.Create, objRegisterDO))
{
return "inserted";
}
else
return "fasle";
}

I correct your data in request. It passing how javascript object
$.ajax({
type:'POST',
contentType: "application/json; charset=utf-8",
url: "Registrationpage.aspx/InsertData",
data: { firstname: firstname, phonenumber: phonenumber,
Organitype: orgtype, OrgnaisaName: orgisaname,
OrgnaisaEmail: orgnisemail,
Stateid: stateid, Districtid: districtid,
Location: location,
Userid: userid, passowrd: password }
dataType: "json",
success: function(response) {
alert('Inserted');
$('#dvreslt').html = "Inserted Successfully";
} ,
error: function (response) { alert('Error') }
});

Related

edit field based on role in crm2011 in javascript code

Anybody know that, how can write a javascript code in crm2011 to give edit option in one field based on security role?
You can use the below script to check the user roles on form load & enable the field. Make the field read-only by default.
Note: It has dependency to use jQuery & Json scripts to be loaded before this script library.
//Check login User has 'case title edit' role
function CheckUserRole() {
var currentUserRoles = Xrm.Page.context.getUserRoles();
for (var i = 0; i < currentUserRoles.length; i++) {
var userRoleId = currentUserRoles[i];
var userRoleName = GetRoleName(userRoleId);
if (userRoleName == "case title edit") {
//make the field editable here...
Xrm.Page.getControl("fieldname").setDisabled(false);
return true;
}
}
return false;
}
//Get Rolename based on RoleId
function GetRoleName(roleId) {
//var serverUrl = Xrm.Page.context.getServerUrl();
var serverUrl = location.protocol + "//" + location.host + "/" + Xrm.Page.context.getOrgUniqueName();
var odataSelect = serverUrl + "/XRMServices/2011/OrganizationData.svc" + "/" + "RoleSet?$filter=RoleId eq guid'" + roleId + "'";
var roleName = null;
$.ajax(
{
type: "GET",
async: false,
contentType: "application/json; charset=utf-8",
datatype: "json",
url: odataSelect,
beforeSend: function (XMLHttpRequest) { XMLHttpRequest.setRequestHeader("Accept", "application/json"); },
success: function (data, textStatus, XmlHttpRequest) {
roleName = data.d.results[0].Name;
},
error: function (XmlHttpRequest, textStatus, errorThrown) { alert('OData Select Failed: ' + textStatus + errorThrown + odataSelect); }
}
);
return roleName;
}
Reference

return response back to ajax from ashx handler in c#

In my application i am using one ashx handler for download ppt, In that i will create one screen shot(current screen as image) and pass that image name to one handler(ashx) from jquery. But am unable to track the downloading status.
If there is any way to return response from that handler to jquery. that is i want to know when that downloading will finish.
my current scenario is like this
jquery will generate one base64 string and pass that string to code behind by ajax call to convert that to image and save that image in one location
on the success call of that ajax request it will get that image name and pass that image name to handler
I am calling that handler by using "window.location.href"
my code
Ajax call for saving the image
$.ajax({
type: "POST",
url: AQ.AMT.Url + "/Home/StoreImage",
//async: false,
data: "{'base64':'" + base64 + "'}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (Data) {
window.location.href = "~/Download/Export.ashx?Type=PPT&downloadToken=" + Data.Result + "&Summary=" + summaryText + "&Note=" + noteText + "&Name=" + name + "&Sample=" + sampleSize + "&SampleColor=" + sampleColor + "&pptType=" + pptType + "&flipName=" + flipName;
//here i need some response
},
error: function (e) {
}
});
Handler code for downloading the ppt
public void ProcessRequest(HttpContext context)
{
DownloadPPT(context);
}
public void DownloadPPT(HttpContext context)
{
//here i will take all parameters
try{
//downloading the ppt
saveFile(pres, "" + name + "-" + FlipName + "-" + System.DateTime.Today.ToLongDateString());//ppt name
}
catch{
}
finally
{
//after ppt download i am deleting that screenshot
if (File.Exists(path))
File.Delete(path);
}
}
I got one solution for this,Instead of using handler for downloading the files i used ajax and jquery. in this in code behind i will create the ppt and save the ppt in some folder and i will pass that name to ajax response and use anchor tag to enable the download in client side itself.
Saving the ppt
[HttpPost]
public JsonResult StoreImage(ExportToPPtRequest request)
{
ExportPptString obj = new ExportPptString();
string downloadToken = Guid.NewGuid().ToString();
string filepath = Server.MapPath("~/Download/Temp/" + downloadToken + ".png");
try
{
using (MemoryStream ms = new MemoryStream(Convert.FromBase64String(request.Base64)))
{
using (System.Drawing.Bitmap bm2 = new System.Drawing.Bitmap(ms))
{
//bm2.Save(filepath);
downloadToken = "";
downloadToken=DownloadPPT(bm2,request);
// bm2.Dispose();
}
// ms.Close();
}
obj.Result = downloadToken;
}
catch (Exception ex)
{
}
var result = Json(obj, JsonRequestBehavior.AllowGet);
return result;
}
public string DownloadPPT(Image imgToReplace, ExportToPPtRequest request)
{
string summaryText = request.Summary;
string note = request.Note;
string sampleSize = request.SampleSize;
string SampleColor = request.SampleColor;
string Type = request.Type;
string name = request.Name;
string pptName = "";
try
{
//if (downloadToken == string.Empty || downloadToken == null)
// throw new Exception("Download Token is unavailable.");
Aspose.Slides.License license = new Aspose.Slides.License();
license.SetLicense("Aspose.Slides.lic");
var _tempPPT = "";
_tempPPT = Server.MapPath("~/Download/Template/ExportPPt.pptx");
Aspose.Slides.Presentation pres = new Aspose.Slides.Presentation(_tempPPT);
pptName= saveFile(pres);//ppt name
}
catch (Exception ex)
{
}
return pptName;
}
public string saveFile(Aspose.Slides.Presentation pres)
{
string downloadToken = Guid.NewGuid().ToString();
try
{
//MemoryStream objMemoryStream = new MemoryStream();
//pres.Save(objMemoryStream, Aspose.Slides.Export.SaveFormat.Pptx);
pres.Save(Server.MapPath("~/Download/Temp/" + downloadToken + ".pptx"), Aspose.Slides.Export.SaveFormat.Pptx);
//byte[] buffer = objMemoryStream.ToArray();
//HttpContext.Current.Response.Clear();
//HttpContext.Current.Response.Buffer = true;
//HttpContext.Current.Response.AddHeader("Content-disposition", String.Format("attachment; filename=\"{0}.pptx\"", PresentationName));
//HttpContext.Current.Response.ContentType = "application/vnd.openxmlformats-officedocument.presentationml.presentation";
//HttpContext.Current.Response.AddHeader("Content-Length", buffer.Length.ToString());
//HttpContext.Current.Response.BinaryWrite(buffer);
//HttpContext.Current.Response.Flush();
//HttpContext.Current.Response.Close();
}
catch (Exception ex)
{
}
return downloadToken;
}
in jquery
$.ajax({
type: "POST",
url: AQ.AMT.Url + "/Home/StoreImage",
//async: false,
data: JSON.stringify({ request: request }),
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (Data) {
var _tempPPT = AQ.AMT.Url + "/Download/Temp/" + Data.Result + ".pptx";
// Trick for making downloadable link
a = document.createElement('a');
a.href = _tempPPT;// window.URL.createObjectURL(xhttp.response);
a.id = "idanchrPPT";
// Give filename you wish to download
var today = new Date();
var dd = today.getDate();
var mm = today.getMonth() + 1; //January is 0!
var yyyy = today.getFullYear();
if (dd < 10) {
dd = '0' + dd
}
if (mm < 10) {
mm = '0' + mm
}
today = dd + '/' + mm + '/' + yyyy;
if (flipName == "")
a.download = "" + name + "-" + today + ".pptx";
else
a.download = "" + name + "-" + flipName + "-" + today + ".pptx";
a.style.display = 'none';
document.body.appendChild(a);
a.click();
$("#idanchrPPT").remove();
//deleting the file
var deleteFiles = {};
deleteFiles.FilePath = Data.Result;
setTimeout(function () {
$.ajax({
type: "Post",
data: JSON.stringify({ deleteFiles: deleteFiles }),
url: AQ.AMT.Url + "/Home/DeleteExportedPPt",
async: true,
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (result) {
},
error: function (result) {
}
});
}, 1000);
},
error: function (e) {
}
});

Jquery Cascading Drop Down how to trigger the change event for all the dropdowns in the chain Sequencially

I have the following jQuery code in my application that drives four cascading dropdowns. I have seen numerous examples online that force the user to select a value by adding a '--Select a Value---' option. However, what I am trying to do is, for the dropdowns, update automatically in the order if one of them changes.
update 2,3,4 if 1 changes and 3,4 if 2 changes, etc.
Dropdown1 Center Dropdown2 Geo Dropdown3 Sup Dropdown4 Emp
This is the jQuery code I have:
$(function() {
$('#divParentaccordion').accordion({ autoHeight: false }).accordion({ collapsible: true });
$('#divGenericaccordion').accordion({ autoHeight: false }).accordion({ collapsible: true });
$('#<% =ddCenter.ClientID %>').change(getGeo());
$('#<% =ddGeo.ClientID %>').change(getSup());
$('#<% =ddSup.ClientID %>').change(getEmp());
// Statements i assume should call the function when the event triggers
})
function getGeo() {
$.ajax({
type: "POST",
url: "./ObservationsReport.aspx/GetGeoList",
data: "{center: '" + $('#<% =ddCenter.ClientID %>').val() + "'}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(response) {
var geos = typeof (response.d) == 'string' ? eval('(' + response.d + ')') : response.d;
$('#<% =ddGeo.ClientID %>').removeOption(/./);
for (var i = 0; i < geos.length; i++) {
var val = geos[i].Code;
var text = geos[i].Description;
$('#<% =ddGeo.ClientID %>').addOption(val, text);
}
}
})
}
function getSup() {
var center = $('#<% =ddCenter.ClientID %>').val();
var geo = $('#<% =ddGeo.ClientID %>').val();
$.ajax({
type: "POST",
url: "./ObservationsReport.aspx/GetSupList",
data: "{center:'" + center + "',geo:'" + geo + "'}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(response) {
var sups = typeof (response.d) == 'string' ? eval('(' + response.d + ')') : response.d;
$('#<% =ddSup.ClientID %>').removeOption(/./);
for (var i = 0; i < sups.length; i++) {
var val = sups[i].SOPId;
var text = sups[i].Name;
$('#<% =ddSup.ClientID %>').addOption(val, text);
}
}
})
}
function getEmp() {
var center = $('#<% =ddCenter.ClientID %>').val();
var geo = $('#<% =ddGeo.ClientID %>').val();
var sup = $('#<% =ddSup.ClientID %>').val();
$.ajax({
type: "POST",
url: "ObservationsReport.aspx/GetEmpList",
data: "{center:'" + center + "',geo:'" + geo + "',sup:'" + sup + "'}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(response) {
var emps = typeof (response.d) == 'string' ? eval('(' + response.d + ')') : response.d;
$('#<% =ddEmp.ClientID %>').removeOption(/./);
for (var i = 0; i < emps.length; i++) {
var val = emps[i].Sop_Id;
var text = emps[i].Name;
$('#<% =ddEmp.ClientID %>').addOption(val, text);
}
}
})
}
What am I doing wrong? I have recently started programming in jQuery; still not completely familiar with how it handles the events and when. Please, any help will be appreciated.
I think your issue is that you're expecting the population of a box from the ajax call to trigger that select's onchange. This is not the case. Changes through javascript do not fire onchange. You will need to fire the onchange yourself.
For example, try changing getGeo to this:
function getGeo() {
$.ajax({
type: "POST",
url: "./ObservationsReport.aspx/GetGeoList",
data: "{center: '" + $('#<% =ddCenter.ClientID %>').val() + "'}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(response) {
var geos = typeof (response.d) == 'string' ? eval('(' + response.d + ')') : response.d;
$('#<% =ddGeo.ClientID %>').removeOption(/./);
for (var i = 0; i < geos.length; i++) {
var val = geos[i].Code;
var text = geos[i].Description;
$('#<% =ddGeo.ClientID %>').addOption(val, text);
}
// *** CALL getSup directly ***
getSup() ;
}
})
}
The key here is the explicit call to getSup as it will not be triggered onchange.

why jquery can't return string/text?

default.aspx
<button id="getGrouper">GetGroupers</button>
<script type="text/javascript">
$(document).ready(function () {
$("#getGrouper").click(function () {
$.ajax({
type: "post",
url: "Groupers.aspx/groupers",
data: "{pid:25}",
dataType: "text",
success: function (data) { alert(data); },
error: function (err) { alert("err:" + err); }
});
return false;
});
});
</script>
groupers.aspx.cs
[WebMethod]
public static string groupers(
int project_id)
{
string employees = "";
foreach (string s in ids.Split(','))
{
u = user.getUserbyUid(Convert.ToInt32(s));
employees += "<a class=\"reply_notify_delete\" href =showuser.aspx?uid=" + u.Uid + "&pid=" + p.Pid + ">" + u.userName + "</a> ";
}
return employees;
}
want to get groupers by a project_id
i want to get string type ,then append it, but i debug the code , it doesn't work , no response , and i set breakpoin , it doesn't go into "groupers" static Method , why ?
Where you have
"{pid:25}",
dataType: "text",
change it to
'{"project_id":25}',
dataType: "json",

insert new line after displayeing each key value pair in javascript object

I have a javascript object which is converted from json to java script object. i want to display its values like after each key value pair, i want to insert new line. but i dont know exactly how to do that. below is my code, please take a look and tell me how i should insert a new line. i tried but its not inserting a new line is diplay.
$.ajaxSetup({
cache: false
//timeout: 1000000
});
//String.prototype.toJSON;
//var the_object = {};
//function concatObject(obj) {
// str = '';
// for (prop in obj) {
// str += prop + " value :" + obj[prop] + "\n";
// }
// return (str);
//}
function concatObject(obj) {
strArray = []; //new Array
for (prop in obj) {
strArray.push(prop + ":\t" + obj[prop]+"*******************************************************\"\n\"");
}
return strArray.join();
}
//var input = "stephen.gilroy1";
function testCAll() {
//var input = $('#Eid').val();
//var input = $document.getElementById('Eid').getValue();
//var input = $('input[name=Employee_NTID]').val();
var keyvalue = {
//ntid: $('#Eid').val()
ntid:"ambreen.haris",
name:"ambreen"
};
$.ajax({
type: "POST",
url: "Testing.aspx/SendMessage",
data: "{}",
//data: "{'ntid':'stephen.gilroy1'}", //working
//data: {'ntid': $('#Eid').val()},
//data: {keyvalue},
//data: { ntid: $('#Eid').val() },
//data: ({ 'ntid': $('input[name=Employee_NTID]').val() }),
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(result) {
alert(result.d);
resultData = eval("(" + result.d + ")");
$("#rawResponse").html(concatObject(resultData));
//$("#response").html(resultData.sn);
},
error: function(result) {
alert("jQuery Error:" + result.statusText);
}
});
}
What's wrong with this?
function concatObject(obj) {
var strArray = []; //new Array
for (var prop in obj) {
strArray.push(prop + ":\t" + obj[prop]);
}
return strArray.join("\n");
}
EDIT:
You're appending HTML. So you should use <br />. Or surround the output with <pre> tags.
function concatObject(obj) {
var strArray = []; //new Array
for (var prop in obj) {
strArray.push(prop + ":\t" + obj[prop]);
}
return strArray.join("<br />");
}

Resources