after a compiling a form needed for register on the website( Registration.cshtml ), the form data are sent in a sqlite db ( successfully). Returning from that, i want to be sent to a Main.cshtml webpage. The problem is that the Action controller that is suposed to render the Main.cshtml view, isn't doing it.
I've tryed changing the Redirect/RedirectToAction and View methods many times, but it was a failure.
return View("Main");
return RedirectToAction("Main");
return JavaScript("window.location = window.location.origin + /Pages/Main");
PagesController.cs
[HttpPost]
public ActionResult Register {
if (insert data in db == true) {
return RedirectToAction("Main");
}
return View();
}
public ActionResult Main(){
return View();
}
Main.cshtml
#{
Layout = "~/Views/Layouts/LoggedMasterPage.cshtml";
ViewBag.Title = "Benvenuto in ETL365";
}
#section Head{
<link rel="stylesheet" href="~/Content/Main.css" />
<script type="text/javascript" src="~/Scripts/Main.js"></script>
}
Part of my Register.js
$("#register").dxButton({
text: "Registrati",
type: "normal",
hint: "Clicca per registrarti",
onClick: function () {
if($('#password').
dxValidator('instance').validate().isValid &&
$('#email').dxValidator('instance').validate().isValid) {
let email = $("#email").dxTextBox('instance').option('value');
let pass = $("#password").dxTextBox('instance').option('value');
$.ajax({
url: window.location.origin + '/Pages/Register',
type: "POST",
data: '{"email":"' + email + '","password":"' + pass + '"}',
contentType: "application/json; charset=utf-8",
dataType: "json",
});
}
}
});
I've already used breakpoints on Main.cshtml, and it actually gets in there after the
return View();
done by the action Main().
What i expect is to be redirected to the mylocalhost:xxxx/Pages/Main
What i get is absolute nothing, I'm always in mylocalHost:xxxx/Pages/Register
You need to redirect to your main page after a successfull ajax call.
$.ajax({
...
success:
{
location.href = 'mylocalhost:xxxx/Pages/Main'
}
...
You cannot use RedirectToAction for AJAX call response because AJAX requests are intended to update the view without reloading whole page. You need to pass the URL as JSON response like this:
[HttpPost]
public ActionResult Register(string email, string password)
{
if (condition) // put your condition here
{
return Json(new {
status = "Success",
url = Url.Action("Main", "Pages")
});
}
// since this controller receives AJAX request, the partial view should be used instead
return PartialView("_Register");
}
Then in AJAX success condition you can check response status and redirect to target URL:
$.ajax({
url: '#Url.Action("Register", "Pages")',
type: "POST",
data: { email: email, password: pass },
success: function (result) {
if (typeof result.status !== undefined && result.status == "Success") {
location.href = result.url; // redirect to main page
}
else {
$('#register').html(result); // refresh partial view
}
}
});
Related issue:
return url.action as json object mvc
Related
I have a link. Its triggers my ajax. I want to open a new page after this triger.
But it's returning back to my ajax after the trigger. There is my code.
HTML
<a onclick="SiparisYazdir(#item.id)" >Print</a>
ajax
function SiparisYazdir(id)
{
$.ajax({
url: '/Order/Print',
type: 'GET',
data: { "value": value, 'id': id } // value is taking from another method.
});
}
controller
public IActionResult Print(int value, int id)
{
//taking model here
return View(model);
}
return View(model) will return the html content of your view
you cant put this html into your desired tag
function SiparisYazdir(id)
{
$.ajax({
url: '/Order/Print',
type: 'GET',
data: { "value": value, 'id': id } // value is taking from another method.,
success:(result)=>{
$('your_desire_elemnt').html(result)
}
});
}
If you want to redirect to another page, I think there is no need ajax here
function SiparisYazdir(id) {
window.location.href = "/Home/Privacy?value=" + value + "&id=" + id;
}
I want to call a view with an ajax call on my current view. The following is my Ajax call that calls a function of my controller.
$.ajax({
type: 'POST',
url: '#Url.Action("EditCertificateObservation", "Frühwarnsystem")',
data: {
serverName: '#Model[0].ServerName',
name: event.data.name,
thumbprint: event.data.thumbprint,
expiringDateStr: event.data.expiringDate,
isChecked: document.getElementById(store + event.data.index).checked,
model: data,
},
});
This code is my controller function that returns a view to load.
[HttpPost]
public ActionResult EditCertificateObservation(string serverName, string name, string thumbprint, string expiringDateStr, bool isChecked, string model)
{
var newModel = JsonConvert.DeserializeObject<List<Store>>(model);
var cert = new Certificate(serverName, name, thumbprint, expiringDateStr);
var server = new Server(serverName);
server.FetchIdByServerName();
if (isChecked)
{
cert.AddToObservation(server.Id);
}
else
{
cert.DeleteFromObservation();
}
return View("Index");
}
To know for you: I call the ajax call with a checkbox on my view, which is dynamically generated. If I debug the controller function get called and runs but the browser doesn't load the view I return.
If you need more information, just ask here.
Thank you for your help
If you want to open a view with after Ajax request than you just have to wait for the response of your controller then you can use success, but you can also use failure or error depend on your need, so your Ajax will be like this:
$.ajax({
type: 'POST',
url: '#Url.Action("EditCertificateObservation", "Frühwarnsystem")',
data: {
serverName: '#Model[0].ServerName',
name: event.data.name,
thumbprint: event.data.thumbprint,
expiringDateStr: event.data.expiringDate,
isChecked: document.getElementById(store + event.data.index).checked,
model: data,
},
success: function (response) {
alert(response.message);
window.location.href = "/Frühwarnsystem/Index";
// or with some parameter
window.location.href ="/Frühwarnsystem/Index?id=" + response.counter;
// or if you prefer with helper ...
window.location.href = '#Url.Action("Frühwarnsystem","Index")';
},
failure: function (response) { alert("failure"); },
error: function (response) { alert("error"); }
});
And to be a little more useful, your controller can send a Json response with some parameter for example, as follow:
[HttpPost]
public JsonResult EditCertificateObservation(string serverName, string name, string thumbprint, string expiringDateStr, bool isChecked, string model)
{
var newModel = JsonConvert.DeserializeObject<List<Store>>(model);
var cert = new Certificate(serverName, name, thumbprint, expiringDateStr);
var server = new Server(serverName);
server.FetchIdByServerName();
if (isChecked)
{
cert.AddToObservation(server.Id);
}
else
{
cert.DeleteFromObservation();
}
// Do some condition here to send an answer ...
string message = "";
int counter = 0;
var response = new { counter, message };
return Json(response);
}
You are calling an ajax POST HTTP request. It means you can download the result of the call and assign it into a javascript variable. This result will not be displayed in the browser as a page. Take a look at examples of $.post here.
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 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.
I have a controller who can return a Success or Error page like this:
[HttpPost]
public ActionResult File_post(HttpPostedFileBase file)
{
if (...)
return View("Success");
else
return View("Error");
}
Those Success and Error pages contains only basic text and are displayed in the Shared/_Layout.cshtml.
In my js I want to call those pages defined by the return View, but how can I do that ?
I tested : window.location.reload();
Which works but it only reloads the actual Index page.
If I try : window.location.href = data.url;
It fails because the page http://xxx/xxx/File_post doesn't exists.
And if I do : $('#main').html(data);
The page have the good looking but the content is empty.
Edit: I am using jquery.fileupload so I have :
<input id="fileupload" type="file" name="file" />
and
$('#fileupload').fileupload(
{
done: function (e, data) {
// Use the return View("Success")
},
fail: function (e, data) {
// Use the return View("Error")
}
});
In my jqXHR.reponseText and data.result there is the good "Success" or "Error" html so I think I need to fill the page with this but how ?
Any ideas ? thanks a lot !
I found how to do it.
As I have in my Layout a <div id="main">
I can use my data.result to fill the page with my "Success" or "Error" message.
So I have :
done: function (e, data) {
$('#main').html(data.result);
}
And
return PartialView("Success");
Now the page is correctly displayed.
You can try with this code
$.ajax({
type: "POST",
url: Settings.YourUrl,
data: "{queryString:'" + searchVal + "'}",
contentType: "application/json; charset=utf-8",
dataType: "html",
success: function (data) {
alert("here" + data.d.toString());
});
And in your View you can add this code
var Settings= {
YourUrl: '#Url.Action("Action","Controller")'
}
The current action can handle only POST requests. So you can create another action to return the view for GET request.
Ex.
public ViewResult Success()
{
return View();
}
you can changed the statusCode to 500 or error code you need;
C#
[HttpPost]
public ActionResult File_post(HttpPostedFileBase file)
{
if (...)
{
return View("Success");
}
else
{
Response.StatusCode = 500;
Response.TrySkipIisCustomErrors = true;
return View("Error");
}
}
JS:
$('#fileupload').fileupload(
{
done: function (e, data) {
// Use the return View("Success")
},
fail: function (e, data) { // http status response != 200
// Use the return View("Error")
}
});