I have a controller action which is getting called by JQuery ajax, and hopefully returniung the contents of "Results" to the requesting page.
So far I have...
Controller
public ActionResult DynCalc(resultsModel model){
...
//code that populates model - all working ok
...
if (Request.IsAjaxRequest())
{
return PartialView("results", model.Results);
}
else
{
return null; //Handle this later
}
}
This passes back a valid model.
Called from the javascript:
$.ajax({
url: "/Test/DynCalc",
type: "POST",
data: $("#frmResults").serialize(), //This part works
dataType: "html",
success: function (result) {
$('#resultsSection').html(result);
$('#hide_panel a').flash("#111", 1000);
}
});
Sucess is never hit. Hopefully somebody can just tell me i'm being daft and missing something obvious?
My partial view results is just a HTML page with javascript on it. If I just have the following
Hello world in my results view, then it works ok, with any script in, it doesn't
Am I on the right track? Should I be changing the type of return on the controller? Or using JSON?
I didn't post the contents of the results page, as It doesn't matter if it's a whole document or simply <b>hi</b> - it does the same thing.
Try to return just a View. Because your result in this case is a complete View (because the action result could be HTML, XML, JSON...whatever).
Use PartialView only as a way to render part of your View.
E.g. on your MasterPage you would like to "always" render user info: #RenderAction("UserInfoAction", "UserController")
var model= {
"PropertyName1":$("#txt1").val(),
"PropertyName1": $("#txt2").val(),
}
$.ajax({
type:"POST",
url: 'Url.Action("DynCalc","ControllerName")',
data: JSON.stringify(model),
contentType: "application/json;charset=utf-8",
success: function (data, status, xhr)
{
alert("The result is : " + status + ": " + data);
},
error: function (xhr)
{
alert(xhr.responseText);
}
});
Related
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.
I'm having trouble extracting data from an AJAX request in ASP.NET Core Razor Pages.
Ajax Request Code (contained in a <script> block on a razor pages .cshtml page:
$("body").ready(function AjaxTest() {
$.ajax({
contentType: 'application/json; charset=utf-8',
dataType: 'text',
url: '/Menus/Admin_MainMenu?action=TestMethod',
method: 'GET',
success: function (data) {
alert("Request Successful" + data);
},
error: function () {
alert("Request Failed");
}
});
})
And the corresponding PageModel method (just as test at the moment):
[HttpGet]
public string TestMethod()
{
string mystring = "success";
return mystring;
}
I know the request works, as I get the alert "Request Successful". However, instead of "Request Successful" being followed by my value of mystring, I get a string of HTML corresponding to the layout of the .cshtml page.
I've tried changing the data type to JSON (both in the AJAX request using dataType, and in the method return type (jsonrequest), but that makes the request fail.
Any help is greatly appreciated. Thanks.
The problem when using dataType: 'text' is that the string may rendered as HTML output instead of simple string. Also declaring function AjaxTest() inside ready event is not a proper way to declare function inside AJAX callback, even the syntax is valid because of scoping issue.
You need to use JsonResult return type instead of string:
public JsonResult OnGetTestMethod()
{
string mystring = "success";
return new JsonResult(mystring);
}
Then use handler parameter inside AJAX call:
$(document).ready(function () {
$.ajax({
dataType: 'json',
url: '/Menus/Admin_MainMenu?handler=TestMethod',
type: 'GET',
success: function (data) {
alert("Request Successful " + data);
},
error: function () {
alert("Request Failed");
}
});
});
Note:
1) The JsonResult mentioned here is not System.Web.Mvc.JsonResult, it uses Microsoft.AspNetCore.Mvc.JsonResult and doesn't have JsonRequestBehavior property.
2) Razor pages uses OnGet and OnPost action method prefixes to deal with HTTP GET and POST respectively, hence the [HttpGet] attribute is unnecessary.
Further references:
Handle Ajax Requests in ASP.NET Core Razor Pages
ASP.NET Core Razor Pages: How to implement AJAX requests
How you doing? I hope its good.
I have a "View" called Create and another two "partial" "views", a view is used to render a bootstrap modal and other to render a table, when I do a post in this modal I must to update that table, but when the model state of the modal is invalid I must call his action, how can I do this? I tryed to use return PartialView("ModalProduto", model);
try something like this
function () {
$.ajax({
url: URL/PartialViewAction,
type: 'GET',
data: $(form1.).serialize(), // or make your objects for the partial
success: function (data) {
$("#placeforthepartialview_as_a_modal").html(data);
},
error: function (e, data) {
}
});
});
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);
}
});
I have a json data object which i need to pass from partial view to view with REDIRECT.
Lets say below is my partial view ( _createEmp.cshtml ):-
Note:- This partial view is in different view or page
<script type="text/javascript">
$(document).ready(function () {
LoadData();
});
function LoadData() {
$.ajax({
type: "GET",
url: baseURL + "Employee/GetEmpInfo",
contentType: "application/json; charset=utf-8",
dataType: "json",
async: true,
success: function (data) {
console.log(data);
**EmpData** = data; // EmpData object
},
error: function (error) {
console.log("Error: " + error);
}
});
}
</script>
<div>
<input type="submit" value="Save" onclick="SetEmpInfo()" />
</div>
And i want to transfer EmpData object to a different view (lets say NewEmp.cshtml), bind something in that view from passed "EmpData object" and open that view (or REDIRECT to view NewEmp.cshtml).
As you are using ajax, you could return the URL from your action and have it redirected in javascript.
Without seeing your controller action you would need to do something like this:
Controller
public ActionResult GetEmpInfo()
{
// Do stuff
return Json(new { success = true, redirecturl = Url.Action("GetEmpInfoSuccess") });
}
Then add something like this to your success handler in javascript:
Javascript (within your success handler)
success: function (data) {
if (data.success == true)
{
window.location = result.redirecturl;
}
}
Issuing a request to Employee/GetEmpInfo for getting the data and on success redirecting to other view - doesn't sound right
I think that you can do all this with one trip to server:
Write an Action that receives all the the parameters that GetEmpInfo receives. Lets call it NewEmployee.
If GetEmpInfo action is your code, reuse it's logic inside NewEmployee action to get EmpData. If it is not your code, you can use issue async request with HttpClient and get EmpData - All this performed on the server
Once you have EmpData you should have everything your need to return a NewEmp view.
In this particular case there is no need in AJAX at all. You can use regular form submit in case that you need to post some data or just a redirect to NewEmployee action.