Cant do redirect (ASP.NET MVC) - c#

I need to do redirect to controller
Here is my controller
[HttpPost]
public ActionResult Index(string question1, string question2, string question3, string question4, string question5, string question6, string question7, string question8, string question9, string question10, Int32 id)
{
QuestionBlock question = new QuestionBlock
{
Question1 = question1,
Question2 = question2,
Question3 = question3,
Question4 = question4,
Question5 = question5,
Question6 = question6,
Question7 = question7,
Question8 = question8,
Question9 = question9,
Question10 = question10,
Interview_Id = id,
};
//TempData["id"] = id;
db.QuestionBlocks.Add(question);
db.SaveChanges();
return Json(new { Result = "Success", Message = "Saved Successfully" }, JsonRequestBehavior.AllowGet);
I try to do it like this
return RedirectToAction("Index", "Questions", new { id = id });
I have this AJAX call in my View. Maybe trouble in it?
<script>
$('.click').on('click', function () {
$('.content').toggle();
});
var counter = 0;
$(document).ready(function () {
$('#save').click(function () {
save();
});
});
function save()
{
$.ajax({
type: 'Post',
dataType: 'Json',
data: {
question1: $('#Question1').val(),
question2: $('#Question2').val(),
question3: $('#Question3').val(),
question4: $('#Question4').val(),
question5: $('#Question5').val(),
question6: $('#Question6').val(),
question7: $('#Question7').val(),
question8: $('#Question8').val(),
question9: $('#Question9').val(),
question10: $('#Question10').val(),
},
url: '#Url.Action("Index", "Questions")',
success: function (da) {
if (da.Result === "Success") {
alert('Вопросы сохранены');
} else {
alert( 'Error'+ da.Message);
}
},
error: function (da) {
alert('Error');
}
});
}
</script>
But redirection not works. Where is my trouble?
Maybe I need to do it not in controller?
Thank's for help

Your current code is returning a JSON response with 2 properties and your main view code is making an ajax call to this action method. So the JSON response returned from the action method will be handled in the success handler of your ajax call. It will not do a redirect unless you explicitly do so.
Even if you replace the return Json with return RedirectToAction, It does not makes sense to use it with the Ajax call. The whole idea of ajaxifying the page is to avoid the traditional page submit - reload experience and replace it with partial page upload behavior (better user experience)
If you absolutely want to redirect to another page, you can do that in the success event handler. But like i mentioned earlier, it does not makes sense to do an ajax post then. Do a normal form post!
if (da.Result === "Success") {
window.location.href="Give the new Url you want to navigate to here";
}
You can use the UrlHelper class to generate the correct url to the other action method and send that as part of your JSON response.
var urlBuilder = new UrlHelper(Request.RequestContext);
var url = urlBuilder.Action("Index", "Questions",new { id= id});
return Json(new { Result = "Success", Message = "Saved Successfully",RedirectUrl=url });
Now in your ajax call , read the RedirectUrl property
if (da.Result === "Success") {
window.location.href=da.RedirectUrl;
}

Have you tried just like this without writing Questions.:
return RedirectToAction("Index", new { id = yourvalue });
EDIT:
Otherwise you can try this:
return RedirectToAction( "Index", new RouteValueDictionary(
new { controller = controllerName, action = "Index", id = id } ) );

Related

How to call RedirectToAction in asynchronous Task methods?

I am using MVC aspnetcore dotnetcore 6.0
I do an authorization with a LoginController. When it is success i want to redirect the user into HomeController. But RedirectToAction does not work. My code is here:
[HttpPost]
[AllowAnonymous]
public async Task<IActionResult> UserLoginAsync(LoginRequestModel requestModel)
{
try
{
if (ModelState.IsValid)
{
LoginResponseModel loginResponseModel = new LoginResponseModel();
var res = _wrapperService.Post<LoginRequestModel, LoginResponseModel>(requestModel, "/api/auth/login");
var tokenRes = GetTokenInfo(res.Result.Data.Token);
HttpContext.Session.SetString("username", requestModel.Email);
var userIdentity = new ClaimsIdentity(tokenRes, "Login");
ClaimsPrincipal claimsPrincipal = new ClaimsPrincipal(userIdentity);
await HttpContext.SignInAsync(claimsPrincipal);
return RedirectToAction("Index", "Home"); // I want to redirect this but it does not work.
return Ok(res.Result);
}
return BadRequest(ModelState);
}
catch (Exception e)
{
var errors = new HttpErrorViewModel()
{
Errors = new List<string>()
};
errors.Errors.Add(e.InnerException.Message);
return BadRequest(errors);
}
}
My Ajax code here:
function LoginWithMail() {
var inputs = {};
$("#form-login .input-login").each(function () {
inputs[$(this)[0].name] = $(this)[0].value;
});
$.ajax({
method: "POST",
url: "/Login/UserLogin/",
data: inputs,
dataType: 'json',
beforeSend: function () {
$("#Email").removeClass("border border-danger");
$("#Password").removeClass("border border-danger");
$("#LoginSpinner").show();
$("#loginResMessages").html("").removeClass();
},
success: function (res) {
console.log(res);
$("#LoginSpinner").hide();
},
error: function (xhr, status, error) {
$("#LoginSpinner").hide();
$("#loginResMessages").html("");
I repeat. I want to redirect this code when it is success. I tried many solutions i found but not worked too.
Please help.
Did you send request to login action with ajax? It can be a problem.
If did you send post request with ajax, just handle the response inside ajax method. If it is success, change the window location to home/index with js.

C# & ASP.NET MVC : call a view with ajax call

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.

How to call api from ASP.NET razor view

Just as stated above, I am not sure how to call an API.
I have done it using fetch in the example below:
fetch("https://localhost:5001/api/patients/add", {
method: "POST",
mode: "cors",
cache: "no-cache",
headers: { "Content-Type": "application/json" },
body: postBody
});}
But it seems there is a different way of doing things in Razor view.
Below is what I have in my API:
// GET: api/Patients/5
[HttpGet("{id}")]
public async Task<ActionResult<Patient>> GetPatient(int id)
{
var patient = await _context.Patient.FindAsync(id);
if (patient == null)
{
return NotFound();
}
return patient;
}
It's just the GET made when creating an API in Visual Studio.
The following ajax call, within a script tag inside the razor page - although this is not best practice - would work as follows:
$.ajax({
type: "GET",
url: "#Url.Action("GetPatient", "Patients")",
data: { id : 1234 },
success: function(result){
//do something with result here
alert(result);
}
});
The second parameter of Url.Action is the Controller Name. This may need to be adapted for yourself.
This is what I ended up doing that worked. Thanks for the help guys!
$(document).ready(function () {
var options = {};
options.url = "https://localhost:44381/api/States";
options.type = "GET";
options.dataType = "json";
options.success = function (states) {
states.forEach(function (state) {
$("#state").append("<option>" + state.stateName + "</option>"
)
});
};
options.error = function () {
$("#msg").html("Error while calling the Web API!");
};
$.ajax(options);
});

Posting AJAX string to MVC Controller

I am trying to post a string (the name of the href the user clicked on) using AJAX to my MVC controller (which it will then use to filter my table results according to the string).
Whilst I have managed to get it to post (at-least according to the alerts) on the AJAX side, it doesn't seem to arrive properly on the controller side and is seen as null in my quick error capture (the if statement).
Please excuse the useless naming conventions for the moment. I've been going through countless methods to try and fix this, so will name properly when I've got a proper solution :).
I've been at work for this for a long while now and can't seem to solve the conundrum so any help is appreciated please! I'm very new to AJAX and MVC in general so I'm hoping it's a minor mistake. :) (FYI I have tried both post and get and both seem to yield the same result?)
Controller:
[Authorize]
[HttpGet]
public ActionResult GetSafeItems(string yarp)
{
using (CBREntities2 dc = new CBREntities2())
{
if (yarp == null)
{
ViewBag.safeselected = yarp;
}
var safeItem = dc.Items.Where(a => a.Safe_ID == yarp).Select(s => new {
Serial_Number = s.Serial_Number,
Safe_ID = s.Safe_ID,
Date_of_Entry = s.Date_of_Entry,
Title_subject = s.Title_subject,
Document_Type = s.Document_Type,
Sender_of_Originator = s.Sender_of_Originator,
Reference_Number = s.Reference_Number,
Protective_Marking = s.Protective_Marking,
Number_recieved_produced = s.Number_recieved_produced,
copy_number = s.copy_number,
Status = s.Status,
Same_day_Loan = s.Same_day_Loan
}).ToList();
// var safeItems = dc.Items.Where(a => a.Safe_ID).Select(s => new { Safe_ID = s.Safe_ID, Department_ID = s.Department_ID, User_ID = s.User_ID }).ToList();
return Json(new { data = safeItem }, JsonRequestBehavior.AllowGet);
}
}
AJAX function (on View page):
$('.tablecontainer').on('click', 'a.safeLink', function (e) {
e.preventDefault();
var yarp = $(this).attr('safesel');
var selectedSafeZZ = JSON.stringify("SEC-1000");
$.ajax({
url: '/Home/GetSafeItems',
data: { 'yarp': JSON.stringify(yarp) },
type: "GET",
success: function (data) {
alert(yarp);
console.log("We WIN " + data)
},
error: function (xhr) {
alert("Boohooo");
}
});
})
** The Alert reveals the correct type: "SEC-1000"
But the console Log shows: WE WIN [Object object]??
I have tried something basic in a new mvc dummy project :
View page basic textbox and a button :
<input type="text" id="txt_test" value="test"/>
<button type="button" class="btn" onclick="test()">Test</button>
<script type="text/javascript">
function test()
{
var text = $("#txt_test")[0].value;
$.ajax({
url: '#Url.RouteUrl(new{ action="GetSafeItems", controller="Home"})',
// edit
// data: {yarp: JSON.stringify(text)},
data: {yarp: text},
type: 'GET',
dataType: 'json',
contentType: "application/json; charset=utf-8",
success: function(data) {
// edit
// alert(JSON.stringify(data));
alert(data.data);
}});
}
</script>
Controller :
[HttpGet]
public ActionResult GetSafeItems(string yarp)
{
return Json(new {data = string.Format("Back end return : {0}",yarp)}
, JsonRequestBehavior.AllowGet);
}
Alert result => {"data":"Back end return : \"test\""}
It's a simple ajax call to a web method. You don't return a view, so I don't understand the use of
if (yarp == null)
{
ViewBag.safeselected = yarp;
}
Also I see an [Authorize] attribute, you perhaps use some authentication and I don't see any authentication header on your ajax call
Try this:
$.each(data, function (i) { console.log("We WIN " + data[i].Serial_Number )});

MVC Jquery POST data, redirect to url from ActionResult

I am currently working with mvc. I have a page with more than one button on, which does complicate things a little. However the button I am using calls a jquery function to post data to the controller. This works as expected and data reaches the action and the action does everything expected except redirect.
The function posts data to the controller, or allows the controller to see the values and build up a url to then redirect to. However the redirect doesnt work, and the function calls a success function as expected. If I put the data return into an alert the code for the page is returned in the alert window not the url.
Here is the code:
<input type="submit" value="Assign" name="Assign" onclick="doRedirect()" />
function doRedirect() {
var action = '#Url.Action("Redirect")';
//alert(action);
var opt = {
type: "POST",
data: {
Team: $('#Team option:selected').val()
},
url: action,
success: RedirectSuccess
};
jQuery.ajax(opt);
}
function RedirectSuccess(data) {
if (data != undefined) {
data;
}
}
public ActionResult Redirect(string Team)
{
var hostName = "http://localhost/test/testpage.aspx?";
var team = "&Team=" + Team;
var filterUrl = Team;
return Redirect(filterUrl);**//this doesnt work**
}
Instead of sending back a redirect result from the action, try sending back the URL you want to redirect to. On the client side, you read the response of the request, and do the redirect by setting window.location.href to the URL you get back from the server.
In your action, you could return the URL as JSON for instance:
return Json(new { url: filterUrl });
And in your success callback, you do this to redirect:
if (data !== undefined && data.url !== undefined) {
window.location.href = data.url;
}
This is what I did instead.
public string Redirect(string Team)
{
var hostName = "http://localhost/test/testpage.aspx?";
var team = "&Team=" + Team;
var filterUrl = hostname + Team;
return filterUrl;
}
function RedirectSuccess(data) {
if (data != undefined) {
window.location = data;
}
}
and on my search success

Categories