I am trying to get data from Active.cshtml.cs file using ajax call.
Here is the jquery code:
var turl = '/Active?handler=Clients/' + id;
$.ajax({
type: "GET",
url: turl,
dataType: "json",
success: function (result) {
alert(JSON.stringify(result));
});
Here is Active.cshtml.cs method
public JsonResult OnGetClients()
{
return new JsonResult("new result");
}
The status is 200 Ok, but it shows the entire webpage in response. Ideally it should return "new result" in Network tab of developer tools. Is it that I have Active.cshtml and Active.cshtml.cs in Pages that creates the confusion? How can I resolve it?
Thanks
For razor pages, you should be passing the parameter value(s) for your handler method in querystring.
This should work.
yourSiteBaseUrl/Index?handler=Clients&53
Assuming your OnGetClients has an id parameter.
public JsonResult OnGetClients(int id)
{
return new JsonResult("new result:"+id);
}
So your ajax code should look something like this
var id = 53;
var turl = '/Index?handler=Clients&id=' + id;
$.ajax({
type: "GET",
url: turl,
success: function (result) {
console.log(result);
}
});
Related
I have this controller action:
[HttpPost]
public ActionResult OrderData(Order order)
{
var result = new { redirectToUrl = Url.Action("SeatSelection", "Orders", new { id = order.ScreeningId }), order };
return Json(result);
}
and I'm trying to pass the order object to another action:
public ActionResult SeatSelection(int id, Order order)
{
var screeningInDb = _context.Screenings.Include(s => s.Seats).Single(s => s.Id == order.ScreeningId);
var viewModel = new SeatSelectionViewModel
{
Seats = screeningInDb.Seats,
NumberOfTicketsOrdered = order.NumberOfTicketsOrdered
};
return View("SeatSelection", viewModel);
}
The problem is - the only parameter I'm receiving in SeatSelection Action is the id parameter, although the order object in OrderData Action is valid. I'm pretty sure the problem is within the way I'm trying to pass the order object, maybe something with the syntax?
Here is the way I'm posting my form data to the OrderData Action:
$.ajax({
type: "POST",
url: '#Url.Action("OrderData", "Orders")',
contentType: "application/json; charset=utf-8",
data: JSON.stringify(orderData),
dataType: "json",
success: function (res) {
alert("Success!");
window.location.href = res.redirectToUrl;
},
error: function (xhr, status, error) {
alert(status);
}
});
Bottom line - What I'm eventually trying to do is to pass the form to a Controller Action where the data will be processed, and then pass the new data to "SeatSelection" view. I had trouble doing this as my post method sends JSON data, so if there is a better way to do what I'm trying to do, I would be happy to learn!
Your model doesn't match SeatSelection parameter signature.
Try:
$.ajax({
type: "POST",
url: '#Url.Action("OrderData", "Orders")',
contentType: "application/json; charset=utf-8",
data: `{"order": ${JSON.stringify(orderData)}}`,
dataType: "json",
success: function (res) {
alert("Success!");
window.location.href = res.redirectToUrl;
},
error: function (xhr, status, error) {
alert(status);
}
});
or (this one just creates a javascript object, which has the two signature properties in):
const sendObj = { id: 0, order: orderData };
$.ajax({
type: "POST",
url: '#Url.Action("OrderData", "Orders")',
contentType: "application/json; charset=utf-8",
data: JSON.stringify(sendObj),
dataType: "json",
success: function (res) {
alert("Success!");
window.location.href = res.redirectToUrl;
},
error: function (xhr, status, error) {
alert(status);
}
});
you can't use
window.location.href = ...
because in this case browser always calls a GET method that can only keep data in a query string with primitives parameters and it doesn't convert Order to a qusery string parameters. This is why you can get only id.
in your case it would be much easier to redirect directly in the action
public ActionResult OrderData(Order order)
{
return RedirectToAction( ( "SeatSelection", "Orders", new { id = order.ScreeningId }), order });
}
or when it is the same controller I usually do this
public ActionResult OrderData(Order order)
{
return SeatSelection (order.ScreeningId, order };
}
but since you are using ajax it will redirect, but will not update your view. For ajax you need a partial view that should be updated on success. So instead of ajax you can only submit form using button. In this case everything will be working ok.
Another way you can use ajax is you can try to split the order in properties and create a query string.
I am trying to change the page after post process of the AJAX process which executes by MVC. I have used it different way maybe my usage might be wrong.
C# MVC code part. I am sending int list which is user list and process and do something.
[HttpPost]
public ActionResult SelectUserPost(int[] usersListArray)
{
// lots of code but omitted
return JavaScript("window.location = '" + Url.Action("Index", "Courses") + "'"); // this does not work
return RedirectToAction("Index"); // this also does not
return RedirectToAction("Index","Courses"); // this also does not
}
My problem is redirect part do not work after the MVC process ends. Process works, only redirect doesn't.
JavaScript code here
// Handle form submission event
$('#mySubmit').on('click',
function(e) {
var array = [];
var rows = table.rows('.selected').data();
for (var i = 0; i < rows.length; i++) {
array.push(rows[i].DT_RowId);
}
// if array is empty, error pop box warns user
if (array.length === 0) {
alert("Please select some student first.");
} else {
var courseId = $('#userTable').find('tbody').attr('id');
// push the id of course inside the array and use it
array.push(courseId);
$.ajax({
url: "/Courses/SelectUserPost",
type: "POST",
data: JSON.stringify(array),
dataType: "json",
contentType: 'application/json; charset=utf-8'
});
}
});
Added this to AJAX and it is not working too
success: function() {
window.location.href = "#Url.Content("~/Courses/Index")";
}
Once you are using AJAX the browser is unaware of the response.
The AJAX success in its current form failed because redirect response code is not in the 2xx status but 3xx
You would need to check the actual response and perform the redirect manually based on the location sent in the redirect response.
//...
success: function(response) {
if (response.redirect) {
window.location.href = response.redirect;
} else {
//...
}
}
//...
Update
Working part for anyone who need asap:
Controller Part:
return RedirectToAction("Index","Courses");
Html part:
$.ajax({
url: "/Courses/SelectUserPost",
type: "POST",
data: JSON.stringify(array),
contentType: 'application/json; charset=utf-8',
success: function (data) {
alert("Successful!");
window.location.href = "#Url.Content("~/Courses/Index")";
}
});
Just deleted
dataType: 'json'
Part because I am using my own data type instead of JSON.
In a Post method within a Controller derived from ApiController what should I return to indicate success to jQuery ?
I've tried HttpResponseMessage but jQuery sees this as an error (even though the argument the jQuery error handler clearly has a 200 status).
The jQuery looks like this :
processParticipantEvent: function(parID, evtType, evtNotes, successFunction, errorFunction){
debugger;
var requestURL = '/api/participantevent';
var json = {"parId" : parID, "evtType": evtType, "evtNotes": evtNotes};
var jsonArray=JSON.stringify(json);
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: requestURL,
data: jsonArray ,
dataType: "json",
success: function (data) { successFunction(data); },
error: function (data) { errorFunction(data); }
});
},
I've read this : Ajax request returns 200 OK, but an error event is fired instead of success which seems like it's touching on the same issue but I suspect it's out of data as it won't work for me ?
Just to be clear all I want to do is to return a plain old 2xx with no data.
As per the documentation:
"json": Evaluates the response as JSON and returns a JavaScript
object. Cross-domain "json" requests are converted to "jsonp" unless
the request includes jsonp: false in its request options. The JSON
data is parsed in a strict manner; any malformed JSON is rejected and
a parse error is thrown. As of jQuery 1.9, an empty response is also
rejected; the server should return a response of null or {} instead.
So if you want to use jQuery ajax you have to return a valid json string, just use the following in your API controller:
return Ok(new {});
Note this is a jQuery ajax "feature", using Angular for example to do an ajax post I can use return Ok(); inside my controller and everything works as expected.
As mentioned by #Beyers the return with OK() just works.
I've created the same structure here and worked.
My Controller has this:
[Route("api/participantevent")]
public IHttpActionResult Test()
{
return Ok("");
}
And at client I've changed your function just to simplify:
processParticipantEvent= function(){
debugger;
var requestURL = '/api/participantevent';
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: requestURL,
data: [{'test': '1'}] ,
dataType: "json",
success: function (data) { alert('success'); },
error: function (data) { alert('error'); }
});
}
Your error is with the requestURL. Its value is absolute and http://api/participantevent does not exist. Try using a relative value.
var requestURL = './api/participantevent';
It seems that if you get an OK response, It is probably not a valid JSON.
I would recommend to you to check the HTTP response in the browser and try to run the JSON.parse function with the responseText and see whether it fails.
I usually declare a class like below:
public class AjaxResult
{
private bool success = true;
private List<string> messages;
public bool Success { get { return success; } set { success = value; } }
public List<string> Messages { get { return messages; } }
public AjaxResult()
{
messages = new List<string>();
}
}
In the controller, the action(to which the ajax request is made) should have JsonResult as return type.
[HttpPost]
public JsonResult Action(string id)
{
AjaxResult result = new AjaxResult();
//Set the properties of result here...
result.Success = true;
result.messages.Add("Success");
return Json(result);
}
3.And your ajax call will look like this:
$.ajax({
type: "POST",
dataType: 'json',
url: /ControllerName/Action,
data: { id: "Test"},
success: function (data) { alert('success'); },
error: function (data) { alert('error'); }
});
Is it possible to accomplish something like this?
<script type="text/javascript">
function getValues( keysArray ) {
var valuesArray = new Array(keysArray.length);
for (var i = 0; i < keysArray.length; i++) {
valuesArray[i] = #this.LocalResources(keysArray[i]);
}
return valuesArray;
}
getValues function will get executed on the browser. Razor is going to execute before the page is send to the browser. there for this wouldn't work.
If you wanted to call the LocalResources method on the server you could to expose a controller action and perform a ajax request from the client.
Perhaps something like this on the browser:
Javascript
function getValues( keysArray ) {
$.ajax({
url: "/Controller/getValues",
type: "POST",
dataType: "json",
contentType: "application/json; charset=utf-8",
async: true,
data: JSON.stringify({ "keysArray" : keysArray }),
success: function (result) {
//result obj is your array of resources
}
});
MVC Controller
public JSONResult getValues(object keysArray)
{
///Build respurce array here
}
Ajax request, or;
loading the list of necessary Resources keys in page and then accessing them by JS.
Hello I'm trying to run a webmethod with ajax from an aspx page. basically I want to redirect to another aspx page with a query string, but I want to do it from <a href>, beacuse it's part of a jquery menu.
from what I learned I can only use ajax to call static webmethods, but I canot redirect from my static function.
visual studio marks it in a red line saying: "an object reference is required for the nonstatic field method or property System.Web.HttpResponse.Redirect(string)"
here is the ajax call:
function redirect_to_profile() {
$.ajax({
type: "POST",
url: "personal_profile.aspx.cs.aspx/redirect_to_profile",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (res) {
alert("success");
},
error: function (res, msg, code) {
// log the error to the console
} //error
});
}
here is the a href:
<a onclick="redirect_to_profile()">Personal Profile</a>
here is the webmethod inside the personal_profile.aspx
[WebMethod]
public static void redirect_to_profile()
{
dbservices db=new dbservices();
string user = HttpContext.Current.User.Identity.Name;
string id = db.return_id_by_user(user);
HttpResponse.Redirect("personal_profile.aspx?id="+id);
}
You will need to return the constructed URL to the client:
public static string redirect_to_profile()
{
dbservices db=new dbservices();
string user = HttpContext.Current.User.Identity.Name;
string id = db.return_id_by_user(user);
return "personal_profile.aspx?id="+id;
}
Then using JavaScript, in the success function of the AJAX call, set the location:
window.location = res;
Or perhaps:
window.location = res.d;
You need to have your web method pass back the ID of the user whose profile you want to redirect to, then in your jQuery success callback set the window.location to the path plus the query string, like this:
function redirect_to_profile() {
$.ajax({
type: "POST",
url: "personal_profile.aspx.cs.aspx/redirect_to_profile",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (res) {
// Redirect to personal_profile.aspx passing it the ID we got back from the web method call
window.location = "personal_profile.aspx?id=" + res;
},
error: function (res, msg, code) {
// log the error to the console
} //error
});
}
[WebMethod]
public static string redirect_to_profile()
{
dbservices db=new dbservices();
string user = HttpContext.Current.User.Identity.Name;
return db.return_id_by_user(user);
}
Instead of doing HttpResponse.Redirect you can send this url that you have generated to you Javascript (response to the ajax call) and then use Javascript code to redirect.
Try this:
function myFun(a) {
var s = null;
var em = document.getElementById(a + 'productno');
if (em != null)
PageMethods.setSession(em.innerText);
window.location.assign("/Product%20Details.aspx");
}