$("#btntest").click(function () {
alert('Called btn test');
var FromDate = $("#FromDate").val();
var ToDate = $("#ToDate").val();
var UserId = $("#ddlUserName")[0].value;
debugger;
$.ajax({
url: '<%:Url.Action("Grid1","GridView") %>',
data: '{"uid":"' + UserId + '","fdate": "' + FromDate + '","tdate":"' + ToDate + '"}',
type: "POST",
contentType: "application/json; charset=utf-8",
success: function (data) {
alert('Success');
alert(data);
window.open("../GridView/Grid1");
}
});
});
on button click GridView action have to call with its respective view(Grid1)
public ActionResult Grid1(string uid, string fdate, string tdate)
{
List<modeldata> list = new List<modeldata>();
DataTable ds1 = new DataTable();
SqlCommand cmd = new SqlCommand("spGettLeadReport", con);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add("#UserID", uid);
cmd.Parameters.Add("#FromDate", fdate);
cmd.Parameters.Add("#ToDate", tdate);
SqlDataAdapter da = new SqlDataAdapter(cmd);
da.Fill(ds1);
foreach (DataRow dr in ds1.Rows)
{
list.Add(new modeldata
{
LeadName = dr["LeadName"].ToString(),
CompanyName = dr["CompanyName"].ToString(),
CreatedOn = Convert.ToDateTime(dr["CreatedOn"]),
CreatedBy = dr["CreatedBy"].ToString(),
// ZoneName = dr["ZONE_NAME"].ToString()
});
}
return View(list);
}
View Is not affecting.on new window it throws an error..
how can i change to the corresponding action view?
please help..
Change your ajax code as below.
$.ajax({
url: '<%:Url.Action("Click Here","Grid1","Controller Name") %>',
data: '{"uid":"' + UserId + '","fdate": "' + FromDate + '","tdate":"' + ToDate + '"}',
type: "POST",
contentType: "application/json; charset=utf-8",
success: function (data) {
alert('Success');
alert(data);
window.open("../GridView/Grid1");
}
});
Related
I works with ASP.net MVC and I have get "Error" from belowe my JavaScript code:
This is my AJAX jQuery code:
$(document).ready(function () {
var dataId;
$(".item2 .small-img").click(function () {
dataId = $(this).data("id");
var url = '#Url.Action("DecorationTest", "Carpet")' + "?Id=" + dataId + "&title=" + '#Url.ToFriendlyUrl(Model.Title.ToString())';
$('#dateLink').prop('href', url);
$.ajax({
url: '/Carpet/CheckCarpet',
type: 'POST',
dataType: 'Json',
data: '{"CarpetImageid":"' + dataId + '"}',
contentType: 'application/json; charset=utf-8',
success: function (data) {
if (data.Success == false)
$('#dateLink').hide();
else
$('#dateLink').show();
alert("Success");
},
error: function (errorThrown) {
alert("Error");
}
});
and this is a controller code:
[HttpPost]
public ActionResult CheckCarpet(int CarpetImageid)
{
bool DecorShow = false;
DecorShow = db.Images.Where(x => x.Id == CarpetImageid).FirstOrDefault().DecorTest;
return Json(new JsonData { Success= DecorShow });
}
what's the reason? Someone knows?
I found the solution.i change url to #Url.Action("CheckCarpet", "Carpet") and fixed.
$(".small-img").click(function () {
dataId = $(this).data("id");
var url = '#Url.Action("DecorationTest", "Carpet")' + "?Id=" + dataId + "&title=" + '#Url.ToFriendlyUrl(Model.Title.ToString())';
$('#dateLink').attr('href', url);
$.ajax({
url:'#Url.Action("CheckCarpet", "Carpet")',
type: 'Post',
dataType: 'Json',
data: '{"CarpetImageid":"' + dataId + '"}',
contentType: 'application/json; charset=utf-8',
success: function (result) {
if (result.Success == false) {
$('#dateLink').hide();
$('.p2').hide();
}
else {
$('#dateLink').show();
$('.p2').show();
}
},
error: function (error) {
alert(error.d);
}
});
});
I am returning HttpResponseMessage from web api and use this in ajax call but getting blank pdf.
my ajax call is
function downloadPDF()
{
$.ajax({
type: "POST",
crossDomain: true,
data: JSON.stringify(UserData),
url: rootUrl + "api/WebAPI/Export",
//dataType: "native",
contentType: "application/json",
//responseType: 'arraybuffer',
//contentType: "application/pdf",
headers: headers,
success: function (data) {
//document.write(data);
alert(data.size);
var blob = new Blob([data]);
var link = document.createElement('a');
link.href = window.URL.createObjectURL(blob);
link.download = "Dossier_" + new Date() + ".pdf";
link.click();
}
}
Convert your HttpResponseMessage(which should be Base64String) to Array Buffer using this function :
function base64ToArrayBuffer(base64) {
var binaryString = window.atob(base64);
var binaryLen = binaryString.length;
var bytes = new Uint8Array(binaryLen);
for (var i = 0; i < binaryLen; i++) {
var ascii = binaryString.charCodeAt(i);
bytes[i] = ascii;
}
return bytes;
}
And then call this function after converting to Array Buffer :
function saveByteArray(pdfName, byte) {
var blob = new Blob([byte], { type: "application/pdf" });
var link = document.createElement('a');
link.href = window.URL.createObjectURL(blob);
var fileName = pdfName + ".pdf";
link.download = fileName;
link.click();
};
So your whole ajax call will look like this :
function downloadPDF()
{
$.ajax({
type: "POST",
crossDomain: true,
data: JSON.stringify(UserData),
url: rootUrl + "api/WebAPI/Export",
//dataType: "native",
contentType: "application/json",
//responseType: 'arraybuffer',
//contentType: "application/pdf",
headers: headers,
success: function (data) {
//document.write(data);
alert(data.size);
var bytes = base64ToArrayBuffer(data);
saveByteArray("Dossier_" + new Date(), bytes);
}
}
Here is my ajax call function on button click
document.getElementById("btnSubmit").onclick = function ()
{
var txtImageName = $('#txtImageName').val();
var CategoryId = $('#cmbCategory').val();
var ImageURL = $('#txtImageURL').val();
var ImageSource = $('#textEditor').val();
var value = CKEDITOR.instances['textEditor'].getData()
alert
$.ajax({
url: "UrlwebService.asmx/InsertImage",
type: 'POST',
data: { ImageName: txtImageName, ImageUrl3x:ImageURL,ImageSource:value,CategoryId:parseInt(CategoryId) },
dataType: 'json',
contentType: "application/x-www-form-urlencoded",
success: function (Categories) {
// states is your JSON array
alert(Categories);
},
error: function (xhr, err) {
alert("I'm in terror");
alert("readyState: " + xhr.readyState + "\nstatus: " + xhr.status);
alert("responseText: " + xhr.responseText);
}
});
};
I change content type to application/json it will also throwing me error
and here I'm calling this method.....
[WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json, UseHttpGet = true)]
public void InsertImage(string ImageName, string ImageUrl3x, string ImageSource, int CategoryId)
{
var result = ImageRepo.InsertImage(ImageName,ImageUrl3x,ImageSource,CategoryId);
var js = new System.Web.Script.Serialization.JavaScriptSerializer();
Context.Response.Write(js.Serialize(result));
}
Expected behavior: User clicks on Register button and record is created in related entity. This has worked up til now but now we have requirement to update the foreign key based on a lookup on the current form. How do I accomplish this? The pasted code below throws error in browser "Error on the creation of record; Error – Bad Request"
// JScript source code
CreateButton = function () {
var fieldTable = crmForm.all.new_registerbutton_d;
var html = "<TABLE border=0 cellSpacing=0 cellPadding=0><TBODY><TR><TD width=0px>" + fieldTable.innerHTML + "</TD><TD width=200><INPUT style='BACKGROUND-COLOR: #d8e8ff' onclick=Button_OnClick() value='Register' type=button></TD></TR></TBODY></TABLE>";
fieldTable.innerHTML = html;
document.all.new_registerbutton.style.display = 'none';
crmForm.all.new_registerbutton_c.innerText = "";
}
Button_OnClick = function () {
//var new_se_registration = new Object();
var invitationName = Xrm.Page.getAttribute("new_name").getValue();
//new_se_registration.new_name = invitationName;
var invitationGUID = Xrm.Page.data.entity.getId().replace('{', '').replace('}', '');
alert(invitationGUID);
var value = new Array();
value[0] = new Object();
value[0].id = invitationGUID;
value[0].name = invitationName;
//var invitation = {
//id: invitationGUID, name: invitationName, entityType: "new_se_registration"
//};
//var invitation= { Id: invitationGUID, LogicalName: "new_se_registration", Name: invitationName };
//value[0].entityType = Xrm.Page.data.entity.getEntityType();
//new_se_registration.new_new_se_invitation_new_se_registid.setValue([{ id: invitationGUID, name: invitationName, entityType: "new_se_registration"}]);
//new_se_registration.new_new_se_invitation_new_se_registid = invitation;
//new_se_registration.new_eventname= Xrm.Page.getAttribute("new_eventname").getValue();
//new_invitationid is the Event id
var lookupItem = new Array;
lookupItem = crmForm.all.new_invitationid.DataValue;
var eventname = lookupItem[0].name;
//new_se_registration.new_eventname = eventname;
lookupItem = crmForm.all.new_invitationid.DataValue;
var new_se_registration = {
new_new_se_invitation_new_se_registid: {
__metadata: { type: "Microsoft.Crm.Sdk.Data.Services.EntityReference" },
Id: invitationGUID,
LogicalName: invitationName
},
new_name: invitationName,
new_eventname: eventname
};
//alert ( eventname);
// end Ek - adding event name
//deleteRecord(new_se_registration.new_name, "new_se_registrationSet");
var reg = Xrm.Page.getAttribute("new_registered").getValue();
if (reg == null) {
reg = "N";
}
if (reg != "Y") {
//Xrm.Page.getAttribute("new_registered").setValue("Y");
//alert(reg);
//return;
createRecord(new_se_registration, "new_se_registrationSet", RegisterCompleted, null);
Xrm.Page.getAttribute("new_registered").setValue("Y");
//Xrm.Page.data.entity.attributes.get("new_registered").setSubmitMode("always");
//Xrm.Page.data.entity.save();
}
else {
alert("\"" + Xrm.Page.getAttribute("new_name").getValue() + "\" has been registered already.");
}
}
function RegisterCompleted(data, textStatus, XmlHttpRequest) {
var new_se_registration = data;
Xrm.Page.data.entity.save();
alert("\"" + Xrm.Page.getAttribute("new_name").getValue() + "\" has been registered successfully.");
}
function checkDuplicate() {
alert("test");
}
function deleteRecord(id, odataSetName) {
var serverUrl = Xrm.Page.context.getServerUrl();
var ODATA_ENDPOINT = "/XRMServices/2011/OrganizationData.svc";
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
datatype: "json",
url: serverUrl + ODATA_ENDPOINT + "/" + odataSetName + "(guid'" + id + "')",
beforeSend: function (XMLHttpRequest) {
//XMLHttpRequest.setRequestHeader("Accept", "application/json");
XMLHttpRequest.setRequestHeader("X-HTTP-Method", "DELETE");
},
success: function (data, textStatus, XmlHttpRequest) {
alert("Record deleted successfully!");
},
error: function (XmlHttpRequest, textStatus, errorThrown) {
alert("Error while deletion – " + errorThrown);
}
});
}
function createRecord(entityObject, odataSetName, successCallback, errorCallback) {
var jsonEntity = window.JSON.stringify(entityObject);
var serverUrl = Xrm.Page.context.getServerUrl();
var ODATA_ENDPOINT = "/XRMServices/2011/OrganizationData.svc";
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
datatype: "json",
url: serverUrl + ODATA_ENDPOINT + "/" + odataSetName,
data: jsonEntity,
beforeSend: function (XMLHttpRequest) {
XMLHttpRequest.setRequestHeader("Accept", "application/json");
},
success: function (data, textStatus, XmlHttpRequest) {
if (successCallback) {
successCallback(data.d, textStatus, XmlHttpRequest);
}
},
error: function (XmlHttpRequest, textStatus, errorThrown) {
if (errorCallback)
errorCallback(XmlHttpRequest, textStatus, errorThrown);
else
alert("Error on the creation of record; Error – " + errorThrown);
}
});
}
Solved. Case sensitivity. Was using wrong case for new_new_se_invitation_new_se_registId.
var new_se_registration = {
new_new_se_invitation_new_se_regist**I**d: {
__metadata: { type: "Microsoft.Crm.Sdk.Data.Services.EntityReference" },
Id: invitationGUID,
LogicalName: invitationName
},
new_name: invitationName,
new_eventname: eventname
};
I get null values in the controller when I process the request using jquery ajax
Controller
[HttpPost]
public ActionResult UpdateAnswers(string answers, string question, string controlid, int eventid)
{
var replacetext=string.Empty;
if (answers.Length>0)
replacetext = answers.Replace("\n", ",");
_service.UpdateAnswers(eventid, replacetext, controlid);
return PartialView("CustomizedQuestions");
}
Jquery - Ajax Code
var test = "{ answers: '" + $("#answerlist").val() + "', question: '" + title + "', controlid: '" + controlid + "', eventid: '" + eventid + "' }";
$.ajax({
url: '#Url.Action("UpdateAnswers")',
type: 'POST',
dataType: 'html',
contentType: 'application/html; charset=utf-8',
context: $(this),
// data: "{ answers: '"+$("#answerlist").val()+"' ,question: '"+ title +"', controlid:'"+ controlid +"',eventid:'"+ eventid+"'}",
data: JSON.stringify(test),
success: function (result) {
$(this).dialog("close");
},
error: function () {
//xhr, ajaxOptions, thrownError
alert('there was a problem saving the new answers, please try again');
}
});
Your contentType is wrong. Why did you set it to application/html when you pass JSON? Try like this:
var test = { answers: $('#answerlist').val(), question: title, controlid: controlid, eventid: eventid };
$.ajax({
url: '#Url.Action("UpdateAnswers")',
type: 'POST',
dataType: 'html',
contentType: 'application/json; charset=utf-8',
context: $(this),
data: JSON.stringify(test),
success: function (result) {
$(this).dialog("close");
},
error: function () {
//xhr, ajaxOptions, thrownError
alert('there was a problem saving the new answers, please try again');
}
});
or using application/x-www-form-urlencoded which is the default:
var test = { answers: $('#answerlist').val(), question: title, controlid: controlid, eventid: eventid };
$.ajax({
url: '#Url.Action("UpdateAnswers")',
type: 'POST',
dataType: 'html',
context: $(this),
data: test,
success: function (result) {
$(this).dialog('close');
},
error: function () {
//xhr, ajaxOptions, thrownError
alert('there was a problem saving the new answers, please try again');
}
});