Controller
public ActionResult Booklist(string bookid) {
return View();
}
View
// other codes
url: 'Index/Booklist',
method: 'POST',
success: function (a) {
var windows = window.open('Index/Booklist');
}
But it seem to invoke dispose(); twice..the reason being the first time it calls return View(); and the second var windows = window.open('Admin/GenerateQRCode');
I need to pass data from controller to javascript in sencha and also pass them to the View..is this possible?
Try this:
public ActionResult Booklist([DataSourceRequest] DataSourceRequest request,string bookid)
{
//result should be your data.
var result=0;
return Json(result, JsonRequestBehavior.AllowGet);
}
// other codes
url: 'Index/Booklist',
method: 'POST',
data:{
'bookid': bookid
},
success: function (result) {
}
Please try this.. Sorry earlier one is not working...
$.ajax({
url: "#Url.Action("Booklist", "Home")",
data: {
'bookid': bookid
},
dataType: 'json',
async: true,
type: 'POST',
success: function (response) {
}
});
public ActionResult Booklist( string bookid)
{
var result=1;
return Json(result, JsonRequestBehavior.AllowGet);
}
This is work for me...
Related
I have an ajax call:
...
$("#testBtn").click(function (e) {
e.preventDefault();
$.ajax({
url: "/profile/GuestList",
data: {"keytype": "1"},
method: "POST",
contentType: "application/json",
success: function (data) {
...
}
});
});
...
and my controller method:
[HttpPost]
public async Task<IActionResult> GuestList([FromBody]string keytype)
{
try
{
return Ok();
}
catch (Exception ex)
{
}
}
So, inititally I wanted to send an enum type, but that didnt work, so I wanted to send an int with value 1 and I kept getting only 0, then I added [FromBody] and it was the same, at last I switched to string just in case, and now Im getting a null value.
Where I went wrong in all this variations?
Create class
public class KeyTypeViewModel
{
public string Keytype { get; set; }
}
Fix action by removing [FromBody]
[HttpPost]
public async Task<IActionResult> GuestList(KeyTypeViewModel viewModel)
And fix ajax by removing contentType: "application/json" :
$.ajax({
url: "/profile/GuestList",
data: {keytype: "1"},
method: "POST",
success: function (data) {
...
}
You need to create a Dto that has property keytype.
public class SomeDto
{
public string Keytype { get; set; }
}
[HttpPost]
public async Task<IActionResult> GuestList([FromBody]SomeDto dto)
You have to update your data in your Ajax call to a string as you are using string as input parameter in your POST method.
...
$("#testBtn").click(function (e) {
e.preventDefault();
$.ajax({
url: "/profile/GuestList",
data: "1",
method: "POST",
contentType: "application/json",
success: function (data) {
...
}
});
});
...
You must stringify your data.
Try the following:
$.ajax({
url: "/profile/GuestList",
data: JSON.stringify({"keytype": "1"}),
method: "POST",
contentType: "application/json",
success: function (data) {
...
}
});
I'm not sure why my ajax success isn't being triggered/called.
My controller is called and the code is executed fine. I'm not returning anything, so my method is a void! Do I need to return something (ActionResult/JSonResult/etc) to get the success to trigger?
Here is my controller code.
public void DeleteEvent(string eventId)
{
diaryEventService.DeleteDiaryEvent(eventId);
}
Here is my ajax call.
$.ajax({
url: '/ManageSpaces/DeleteEvent',
dataType: 'json',
data: {
eventId: eventId,
},
success: function() {
//var obj = JSON.parse(doc);
var myCalendar = $('#fullcalendar');
myCalendar.fullCalendar();
myCalendar.fullCalendar('removeEvents', eventId);
$("#eventDetails").collapse('toggle');
}
});
Yes, you need to return JsonResult:
[HttpPost]
public JsonResult DeleteEvent(string eventId)
{
diaryEventService.DeleteDiaryEvent(eventId);
return Json("{status:"OK"}");
}
Since you are changing back-end data, set it to POST:
$.ajax({
url: '/ManageSpaces/DeleteEvent',
method: 'POST',
dataType: 'json',
data: {
eventId: eventId,
},
success: function(response) {
if(response.status=="OK"){
var myCalendar = $('#fullcalendar');
myCalendar.fullCalendar();
myCalendar.fullCalendar('removeEvents', eventId);
$("#eventDetails").collapse('toggle');
}else{
console.log("Error occured")
}
}
});
i create a web method and now i'm calling this in my java script file but it give an path error,it is not able to find path what i'm giving ..
Web method code is :
[System.Web.Services.WebMethod]
public static int ItemCount(string itemId)
{
int val = 0;
Item itm = Sitecore.Context.Database.GetItem(itemId);
val = itm.Children.Count;
return val;
}
java script function calling like as:
function GetItemCount(itemId) {
var funRes = "";
debugger;
try {
if (itemId != null) {
jQuery.ajax({
cache: false,
type: "POST",
contentType: "application/json; charset=utf-8",
url: "/Views/GetItem.aspx/ItemCount",
data: { itemId: itemId },
dataType: "json",
async: false,
success: function (data) {
funRes = data.result;
},
error: function(err) {
alert(err.responseText);
}
});
}
} catch (ex) {
alert(ex.message);
}
return funRes;}
while i'm giving exact path for the C# method class but it's not working give an error on console, can anyone suggest me what i'm missing here..
There are few rules for ajax to work with asp.net.
Your WebMethod should be public and static.
If your WebMethod expects some parameter(s) than these parameter(s) must be passed as data in ajax.
Name of parameter(s) should be same in WebMethod and in data part of ajax.
Data passed from ajax should be in json string.For this you can use JSON.stringify or you will have to surround the values of parameter(s) in quotes.
Please check the below sample ajax call
function CallAjax()
{
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: "Default.aspx/CallAjax",
data: JSON.stringify({ name: "Mairaj", value: "12" }),
dataType: "json",
async: false,
success: function (data) {
//your code
},
error: function (err) {
alert(err.responseText);
}
});
}
[WebMethod]
public static List<string> CallAjax(string name,int value)
{
List<string> list = new List<string>();
try
{
list.Add("Mairaj");
list.Add("Ahmad");
list.Add("Minhas");
}
catch (Exception ex)
{
}
return list;
}
EDIT
If you use GET in ajax than you need to enable your webmethod to be called from GET request. Add [System.Web.Script.Services.ScriptMethod(UseHttpGet = true)] on top of WebMetod
[System.Web.Services.WebMethod]
[System.Web.Script.Services.ScriptMethod(UseHttpGet = true)]
public static int ItemCount()
Just Modify the javascript function as below
function GetItemCount(itemId) {
var funRes = "";
debugger;
try {
if (itemId != null) {
jQuery.ajax({
type: "GET",
url: "/Views/GetItem.aspx",
data: 'itemID=' + itemId,
contentType: "application/html",
dataType: "html",
success: function (response) {
funRes= response.result;
}
});
}
} catch (ex) {
alert(ex.message);
}
return funRes;
}
I am not sure it is a solution for every question subject which web method not fire. But I discovered today when there is ' char in the string. Web Method not firing.
I want to send my ajax data through post method, from my view but I don't how to receive it in the controller method. here is ajax code :
$.ajax({
contentType: 'application/json; charset=utf-8',
method: 'post',
async: false,
url: "Gateway/DB_Rola",
data:Obj,
success: function (Data) {alert("Good");},
error: function () {alert("Error");}
});
Here is controller code :
[HttpPost] // bindig data with class thing
public JsonResult DB_Rola(thing things)
{ ... }
modal class code :
public class thing
{
public int surah { get; set; }
public int ayah { get; set; }
public string verse { get; set; }
}
Now I don't know how to get that object in controller method. I have tried it with get method , there its working fine, problem is with post...
Please try with the below code snippet.
JS
<script>
$(document).ready(function () {
var things = new Object();
things.surah = 1;
things.ayah = 2;
things.verse = "3";
$.ajax({
url: "Home/DB_Rola?count=" + 1,
type: 'POST',
contentType: 'application/json; charset=utf-8',
dataType: 'json',
async: false,
data: JSON.stringify(things),
success: function (result) {
alert('success');
},
error: function (result) {
alert('boo!');
},
});
});
</script>
MODEL
public class thing
{
public int surah { get; set; }
public int ayah { get; set; }
public string verse { get; set; }
}
CONTROLLER
public class HomeController : Controller
{
[HttpPost]
public ActionResult DB_Rola(thing things)
{
return Json(new { IsSuccess = true });
}
}
OUTPUT:
With/Without Count
Update 1 : pass the list[] of objects instead of single object things
<script>
$(document).ready(function () {
var things = new Array();
var test1 = new Object();
test1.surah = 1;
test1.ayah = 2;
test1.verse = "3";
things.push(test1);
var test2 = new Object();
test2.surah = 11;
test2.ayah = 22;
test2.verse = "33";
things.push(test2);
$.ajax({
url: "Home/DB_Rola?count=" + 1,
type: 'POST',
contentType: 'application/json; charset=utf-8',
dataType: 'json',
async: false,
data: JSON.stringify(things),
success: function (result) {
alert('success');
},
error: function (result) {
alert('boo!');
},
});
});
</script>
[HttpPost]
public ActionResult DB_Rola(List<thing> things,int count)
{
return Json(new { IsSuccess = true });
}
Try this It's just an Example,
function SearchProduct () {
var isExcluded = $('#chkisExcluded').is(':checked');
$.ajax({
type: "POST",
url: '#Url.Action("SearchProductManagement","ProductListManagement")',
data: { isExcluded: isExcluded,},
success: function (data) {
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
alert(XMLHttpRequest.responseText);
}
});
}
Controller
public JsonResult SearchProductManagement(bool isExcluded)
{
//Your code
return Json(data, JsonRequestBehavior.AllowGet);
}
View
<input type="button" value="Go" onclick="return SearchProduct();" class="button next" />
assuming Obj = {surah:somvalue, ayah:somevalue, verse:somevalue}
The problem is the extra parameter count, you don't have a post action that handles count,
so try:
$.ajax({
contentType: 'application/json; charset=utf-8',
method: 'post',
async: false,
url: "Gateway/DB_Rola,
data:Obj,
success: function (Data) {alert("Good");},
error: function () {alert("Error");}
});
forgive me if this question is too silly or already asked I googled a lot but I didnt get anything I want. I need to pass a byte array to server side using ajax but its not working as planned my current code is given below
var bytes = [];
for (var i = 0; i < data.length; ++i) {
bytes.push(data.charCodeAt(i));
}
$.ajax({
url: '/Home/ImageUpload',
dataType: 'json',
type: 'POST',
data:{ data:bytes},
success: function (response) {
alert("hi");
}
});
Upload Method
[HttpPost]
public ActionResult ImageUpload(byte[] data)
{
ImageModel newImage = new ImageModel();
ImageDL addImage = new ImageDL();
newImage.ImageData = data;
addImage.AddImage(newImage);
return Json(new { success = true });
}
I know something wrong with my program but I cant find it please help me to solve this
Better do this:
$.ajax({
url: '/Home/ImageUpload',
dataType: 'json',
type: 'POST',
data:{ data: data}, //your string data
success: function (response) {
alert("hi");
}
});
And in controller:
[HttpPost]
public ActionResult ImageUpload(string data)
{
var bytes = System.Text.Encoding.UTF8.GetBytes(data);
//other stuff
}