I have this code that got properly delivered to its controller counterpart.
but for some reason the search model data was only nulls,while the pageNumber is received properly
did i made a mistake somewhere?
$("#NextResult").click(function () {
var xData= document.getElementById("x1").value;
var yData= document.getElementById("y1").value;
var searchModel = {
xval: xData,
yval: yData,
};
var pageNumber = #Model.Page +1;
$.ajax({
url: "/Work/FilterData",
type: "GET",
data: { 'searchModel': searchModel, 'pageNumber': pageNumber },
error: function (xhr, ajaxOptions, thrownError) {
alert(thrownError);
}
}).success(function (response) {
$('#datas').html(response)
})
});
the Controller is as such
[HttpGet]
public ActionResult FilterData(WorkSearchModel searchModel,int? pageNumber)
{
EDIT:
as suggested i tried doing doing both on a different project (this makes the function uncallable so i presume there's an error somewhere)
$("#NextResult").click(function () {
var xData= document.getElementById("x1").value;
var yData= document.getElementById("y1").value;
var searchModel = {
xval: xData,
yval: yData,
pageNumber = #Model.Page +1
};
$.ajax({
url: "/Work/FilterData",
type: "GET",
data: searchModel,
error: function (xhr, ajaxOptions, thrownError) {
alert(thrownError);
}
}).success(function (response) {
$('#datas').html(response)
})
});
i also have tried to do this but nothing works (this gives null values for both searchmodel and pagenumber now)
$.ajax({
url: "/Work/FilterData",
type: "GET",
data: JSON.stringify(searchModel, pageNumber),
contentType: "application/json;",
I would change the call from a GET to POST
One solution is to send the parameters one by one in the query string like this
$("#NextResult").click(function () {
var xData= document.getElementById("x1").value;
var yData= document.getElementById("y1").value;
var pageNumber = #Model.Page +1;
$.ajax({
url: "/Work/FilterData?xval=xData&yval=yData&pageNumber=pageNumber",
type: "GET",
error: function (xhr, ajaxOptions, thrownError) {
alert(thrownError);
}
}).success(function (response) {
$('#datas').html(response)
})
});
And the controller
[HttpGet]
public ActionResult FilterData(int xval, int yval, int? pageNumber)
Related
I'm working with the Ajax and jQuery in my app. When I return a query result it's not showing me that result. The Code is given below:
asmx page Code
[WebMethod, ScriptMethod]
public void Getusertimelist(string id)
{
List<UserhoursList> employeelist = new List<UserhoursList>();
using (SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["dbcon"].ConnectionString))
{
con.Open();
SqlCommand command12 = new SqlCommand(" SELECT CONVERT(TIME, DATEADD(s, SUM(( DATEPART(hh, Total_time) * 3600 ) + ( DATEPART(mi, Total_time) * 60 ) + DATEPART(ss, Total_time)), 0)) From Todaywork Where Id='"+id+"'", con);
string getvalue = command12.ExecuteScalar().ToString();
UserhoursList employee = new UserhoursList();
employee.Total_Time = getvalue;
employeelist.Add(employee);
con.Close();
}
JavaScriptSerializer js = new JavaScriptSerializer();
Context.Response.Write(js.Serialize(employeelist));
//return id;
}
Ajax Code
<script type="text/javascript">
$(document).on("click", ".get_time", function () {
var timeid = $(this).data('id');
$.ajax({
url: 'UserTotaltime.asmx/Getusertimelist',
method: 'post',
data: { id: timeid },
success: function (data) {
//alert(data);
},
error: function (err) {
}
});
});
$(document).ready(function () {
$(".get_time").click(function () {
$.ajax({
url: "UserTotaltime.asmx/Getusertimelist",
dataType: "json",
method: 'post',
success: function (data) {
alert(data[0].Total_Time);
// var prodetail = document.getElementById('textbox').HTML = 2;
document.getElementById("UserTime").innerHTML = data[0].Total_Time;
prodetail.html(data[0].Total_Time);
},
error: function (err) {
}
});
});
});
</script>
It's not showing me the answer because when I remove that (string id) parameter then it works perfectly. When I use it's not showing me the answer. I want to complete my project but this error not pushing me. Any help plz.
Your first request looks good. But in your second request, I don't see that you're using the jQuery DataTable data option.
$(".get_time").click(function () {
$.ajax({
url: "UserTotaltime.asmx/Getusertimelist",
dataType: "json",
method: 'post',
// Where is data: { id: timeid }?
success: function (data) {
alert(data[0].Total_Time);
// var prodetail = document.getElementById('textbox').HTML = 2;
document.getElementById("UserTime").innerHTML = data[0].Total_Time;
prodetail.html(data[0].Total_Time);
},
error: function (err) {
}
});
I think it will work if you change data to send a string
$.ajax({
url: 'UserTotaltime.asmx/Getusertimelist',
method: 'post',
data: '{ "id": ' + timeid + '}',
success: function (data) {
//alert(data);
},
error: function (err) {
}
});
an alternative is do something like
var dat = {}
dat.id = timeid
$.ajax({
url: 'UserTotaltime.asmx/Getusertimelist',
method: 'post',
data: JSON.stringify(dat),
success: function (data) {
//alert(data);
},
error: function (err) {
}
});
Basically, I am trying to call controller from views using jQuery ajax but it's not calling controller.
What I have to do is passing my token value from registration page to controller so that I will use its value for user registration.
< script type = "text/javascript" >
document.getElementById('LoginWithAmazon').onclick = function() {
options = {
scope: 'profile'
};
amazon.Login.authorize(options,
function(response) {
if (response.error) {
alert('oauth error ' + response.error);
return;
}
GetProfileInfo(response.access_token);
});
function GetProfileInfo(token) {
$.ajax({
type: 'GET',
url: '/Account/ProfileInfo',
data: {
token: 'abc'
},
cache: false,
success: function(result) {
alert(result);
}
});
}
function receiveResponse(response) {
if (response != null) {
for (var i = 0; i < response.length; i++) {
alert(response[i].Data);
}
}
}
return false;
};
< /script>/
Here below is my controller code
public JsonResult ProfileInfo(string token) {
return Json("test", JsonRequestBehavior.AllowGet);
}
I need to pass the token value from registration page to my controller
Try to change this in the controller
return Json("test", JsonRequestBehavior.AllowGet);
into
enter code herereturn Json(new { value="test" }, JsonRequestBehavior.AllowGet);
and change your js to be like this
$.ajax({
type: 'GET',
url: '/Account/ProfileInfo',
data: JSON.stringify({
token: 'abc'
}),
cache: false,
success: function(result) {
alert(result);
}
});
Finally, i have solved the problem.I am unable to call the account controller so i have used my home controller for this purpose.Here below is the code that i have used for calling controller :
<script type="text/javascript">
document.getElementById('LoginWithAmazon').onclick = function() {
options = { scope : 'profile' };
amazon.Login.authorize(options, function(response) {
if ( response.error ) {
alert('oauth error ' + response.error);
return;
}
GetProfileInfo(response.access_token);
});
function GetProfileInfo(token)
{
var url = "/home/ProfileInfo?token=" + token;
var request = $.ajax({
url: url,
method: "GET",
dataType: "json"
});
request.done(function (msg) {
var data = [];
alert(msg);
});
request.fail(function (jqXHR, textStatus) {
});
}
}
</script>
I have an asp.net mvc application and want to upload files and form data with ajax and also want to use [ValidateAntiForgeryToken]-Attribute. But i not want use formData class client side (because of brower support).
My client code:
function sendMessage(id) {
if (window.FormData !== undefined) { //
var fileData = new FormData();
fileData.append('profileId', id);
fileData.append('title', $('#Message_Title').val());
fileData.append('text', $('#Message_Text').val());
fileData.append('__RequestVerificationToken', $('[name=__RequestVerificationToken]').val());
var files = $("#Message_Image").get(0).files;
if (files[0]) {
fileData.append(files[0].name, files[0]);
}
$.ajax({
url: '/Manage/SendMessage',
type: "POST",
contentType: false,
processData: false,
data: fileData,
success: function (result) {
alert(result);
},
error: function (err) {
alert(err.statusText);
}
});
} else {
var files2 = $("#Message_Image").get(0).files;
$.ajax({
url: '/Manage/SendMessage',
type: 'POST',
//contentType: false,
//processData: false,
data: {
profileId: id,
title: $('#Message_Title').val(),
text: $('#Message_Text').val(),
//image: files2[0], <--- IF I UNCOMMENT THIS IT NOT WORKS ANYMORE
__RequestVerificationToken: $('[name=__RequestVerificationToken]').val()
},
success: function (result) {
},
error: function (err) {
alert(err.statusText);
}
});
}
};
Server code:
[HttpPost]
[ValidateAntiForgeryToken]
public JsonResult SendMessage(int? profileId, string title, string text)
{
HttpPostedFileBase file = Request.Files["Image"];
HttpFileCollectionBase files = Request.Files;
return Json(null, "text/html");
}
I'm trying to do a ajax request to my controller in C#, but it never reaches the controller - I get a type Error saying "query is undefined".
Here is my ajax script:
$(document).ready(function () {
$.ajax({
url: '/Account/GetAllGamesWithRoles',
type: 'POST',
data: {},
success: function (games) {
debugger;
Games = games;
BuildGames(games);
},
error: function() {
}
});
});
Here is my controller action:
[HttpPost]
public ActionResult GetAllGamesWithRoles()
{
var result = MockGames();
return new JsonResult{ Data = result, MaxJsonLength = Int32.MaxValue};
}
try this
$(document).ready(function () {
alert('called before ajax');
$.ajax({
url: "/Account/GetAllGamesWithRoles",
type: "POST",
data: {'test':'testcall'},
success: function (data) {
Games = data.Data;
BuildGames(Games);
},
error: function (request, textStatus, errorThrown) {
alert("Status: " + textStatus + "Error: " + errorThrown);
}
});
});
[HttpPost]
public JsonResult GetAllGamesWithRoles(string test)
{
var result = MockGames();
return Json{ Data = result, JsonRequestBehavior.AllowGet};
}
I' m new to MVC and was trying out some things but I can' t get this to work.
I have this script that should insert a partial view inside the page based on the dropdownlist selection.
$(function () {
$('#ddTipologiaFattura').change(function () {
var selectedID = $(this).val();
$.ajax({
url: '/Admin/Fatturazione/GetPartial/' + selectedID,
contentType: 'application/html; charset=utf-8',
type: 'GET',
dataType: 'html'
})
.success(function (result) {
$('#partialPlaceHolder').html(result);
})
.error(function (xhr, status, error) {
alert(status + '\n' + error)
});
});
});
This is my controller ~/Areas/Admin/Controllers/FatturazioneController.cs
[RouteArea("Admin")]
[Route("Fatturazione/{action}")]
public class FatturazioneController : Controller
{
private MyEntity db = new MyEntity();
public ActionResult GetPartial(int partialViewId)
{
if (partialViewId == 0)
{
var fatturaAziendaVM = new FatturaPerAziendaViewModel();
ViewBag.Intestatario = new SelectList(db.Azienda, "AziendaNome", "AziendaNome");
return PartialView("~/Areas/Admin/Views/Fatturazione/_ListaAziende.cshtml", fatturaAziendaVM);
}
var fatturaVM = new FatturaViewModel();
return PartialView("~/Areas/Admin/Views/Fatturazione/_Intestatario.cshtml", fatturaVM);
}
I keep getting a Not Found error by the script.
What am i doing wrong?
Your route only accounts for the action, not for the Id, which is why it's failing. You should either update the route per action to account for the Id, or append the id as a query string parameter.
$.ajax({
url: '/Admin/Fatturazione/GetPartial?partialViewId=' + selectedID,