Redirect after Ajax - c#

I have a mvc project, what I want to do is this:
I am sending an ajax request from my JS script. After processing it I want to redirect to a page with a model.
Now I tried sending a form as the ajax response and submit it like so:
sb.Append("<html>");
sb.AppendFormat(#"<body onload='document.forms[""form""].submit()'>");
sb.AppendFormat("<form name='form' action='{0}' method='post'>", "url..");
sb.AppendFormat("<input type='hidden' name='result' value='{0}'>", val1);
.....
And on the JS:
success: function (result) {
var form = $(result);
$(form).submit();
}
But this way i need to specify each post param, I want to send the entire model object.
How can I do that?
Edit
Full steps:
1.Using an MVC APP.
2.I submit button in my view which redirects the user to my JS code.
3.Js code sends an Ajax request to a MVC page called 'Transaction'.
4.C# code doing some actions and now I need to redirect the usr to a page named EOF with ALOT of post params, thats why I want to pass it as a ViewModel.

As you are using ajax, you could return the URL from your action and have it redirected in javascript:
Controller
public ActionResult Transaction()
{
// Do stuff
return Json(new { success = true, redirecturl = Url.Action("RedirectedAction") });
}
Then add something like this to your success handler in javascript:
Javascript (within your success handler)
success: function (result) {
if (result.success == true)
{
window.location = result.redirecturl;
}
}

You can try this:
public ActionResult YourMethod(string param)
{
//what ever you want to do with reference no
return View("EOF");
// or, if you want to supply a model to EOF:
// return View("EOF", myModel);
}

Related

Redirect to action with JsonResult

I have a view. When user clicks on a button in my view, I am trying to get some data from my view without reloading my view through an AJAX POST to display some data.
This is the method in my controller :
[HttpPost]
public JsonResult GetUserTraj()
{
var userTrajList =
DBManager.Instance.GetUserTraj(Session["UserName"].ToString());
return Json(userTrajList);
}
This returns a Json Result. I am trying to implement session now. So if the session has expired, I want user to be redirected to the Login view. In the above case if the session expires Session["UserName"] becomes null and an exception is raised.
[HttpPost]
public JsonResult GetUserTraj()
{
if (Session["UserName"] != null)
{
var userTrajList =
DBManager.Instance.GetUserTraj(Session["UserName"].ToString());
return Json(userTrajList);
}
else
{
RedirectToAction("Login", "Login");
return Json(null);
}
}
I tried the above code. But it doesn't work. It does not redirect the user to the Login view. I tried return RedirectToAction("Login", "Login");. But that doesn't work since the controller action method cannot return something other than JsonResult. Please help me find a solution for the same.
If you use AJAX to request a page, it's cant redirect in browser.
You should response a status code, and then use javascript to redirect in front, like this
[HttpPost]
public JsonResult GetUserTraj()
{
if (Session["UserName"] != null)
{
var userTrajList =
DBManager.Instance.GetUserTraj(Session["UserName"].ToString());
return Json(userTrajList);
}
else
{
//RedirectToAction("Login", "Login");
return Json(new {code=1});
}
}
You need write this condition Inside of your Ajax success call to reload login screen,
if(result.code ===1){
window.location = 'yourloginpage.html'
}
You can't redirect user to a new page using ajax. For this you have to send some flag at client side and then need to use that flag to identify that session has been expired.
Following code will help you:
[HttpPost]
public JsonResult GetUserTraj()
{
if (Session["UserName"] != null)
{
var userTrajList = DBManager.Instance.GetUserTraj(Session["UserName"].ToString());
return Json(new { Success = true, Data = userTrajList});
}
else
{
return Json(new { Success = false, Message = "Session Expired"});
}
}
jQuery
$.ajax({
url: "any url",
dataType: '',
contentType: "------",
success: function(response){
if(response.Success){
// do stuff
}else{
window.location.href = "/YourLoginURL.aspx"
}
}
});
Just try it
[HttpPost]
public ActionResult GetUserTraj()
{
if (Session["UserName"] != null)
{
var userTrajList =
DBManager.Instance.GetUserTraj(Session["UserName"].ToString());
return Json(userTrajList);
}
else
{
RedirectToAction("Login", "Login");
return Json(null);
}
}
Edit
also your login action should be return json result, if you wont the page reloading
ActionResult is an abstract class that can have several subtypes.
ActionResult Subtypes
ViewResult - Renders a specifed view to the response stream
PartialViewResult - Renders a specifed partial view to the response stream
EmptyResult - An empty response is returned
RedirectResult - Performs an HTTP redirection to a specifed URL
RedirectToRouteResult - Performs an HTTP redirection to a URL that is determined by the
routing engine, based on given route data
JsonResult - Serializes a given ViewData object to JSON format
JavaScriptResult - Returns a piece of JavaScript code that can be executed on the client
ContentResult - Writes content to the response stream without requiring a view
FileContentResult - Returns a file to the client
FileStreamResult - Returns a file to the client, which is provided by a Stream
FilePathResult - Returns a file to the client
Controller
This is a common function may used as a generic one as you wish
public void logoutJson()
{
Response.StatusCode = (int)HttpStatusCode.BadRequest; //Send Error Status to Ajax call
Response.StatusDescription = Url.Action("Index", "Account"); //Url you want to redirect
}
Script
Just paste this code in the View Pages you want to use it. So it will automatically handle All AJAX calls you wanted.
$(document).ready(function () {
$.ajaxSetup({
'complete': function (xhr, textStatus) {
if (xhr.status!="200") {
window.location.replace(xhr.statusText); //Redirect to URL placed in Response.StatusDescription
}
}
});
});
Example
Just call the function for manually fail the AJAX Request and the script in client side handle to redirect to login page.
public JsonResult TestAction()
{
if (null == Session["EmpId"])
{
logoutJson(); //Just call the function
}
}

How to make Angular POST to C# Asp.Net MVC Controller?

I have looked around, but have not found anything (Angular post) that can actually make a successful call to a MVC Controller. I know there are a lot of Angular/.Net devs out there. Can I get some help?
Let's keep answers bare bones simple!!!
If I set a linebreak on the controller, I can see that this code is not actually hitting the controller.
HTML
<!-- I click this button -->
<input type="button" value="click" onclick="postit()" />
Javascript/Angular Post
function postit() {
$http({
method: 'POST',
url: 'Home/Give/',
data: { id: 4 }
}).success(successFn).error(errorFn);
}
function successFn() {
alert("success");
}
MVC C# Controller
[AcceptVerbs("OPTIONS")]
public ActionResult Give(int id)
{
var response = "some response" + id.ToString();
return Json(new JavaScriptSerializer().Serialize(response));
}
king Puppy, I've seen a few responses that dictate that the controller parameters should be an object that matches the object that is being sent, however, it seems that it's a little more forgiving than that. Consider the following example (I've updated your function a little):
Javascript:
$scope.postIt = function() {
var data = {
id = 4
};
$http
.post('Home/Give', data)
.success(function(data, status, headers, config) {
successFn();
})
.errors(function(data, status, headers, config) {
errorFn();
});
};
function successFn() {
alert("success");
};
function errorFn() {
alert("error");
};
MVC:
public ActionResult Give(int id)
{
var response = "some response" + id.ToString();
return Json(new JavaScriptSerializer().Serialize(response));
}
If you set a breakpoint, you will see that the id passed in is 4.
If you needed to pass in an object (so more than just one id), you could either create a matching class or struct on the controller side, or have multiple parameters (provided that they are simple value types)
ie:
public JsonResult Give (int id, int reasonId)
{
...
}
Anyway, I realize the post is old, but perhaps it will help you or others.
#kingPuppy this is my way to how to make angularjs post to mvc controller
first, html button for passing the angular js button click function;
<button class="btn btn-info" id="runButton" ng-click="runService('Hi')">Run</button>
so runService angular click (ng-click) function;
// Operation Type is my mvc controller's param
$scope.runService = function (optionType) {
$http({
url: '/System/RunService',
method: "POST",
data: {operationType : optionType}
}).then(function onSuccess(response) {
// Handle success
console.log(response);
}).catch(function onError(response) {
// Handle error
console.log(response);
});
}
And finally this is system controller's action;
NOT : Dont forget to [HttpPost] attribute
[HttpPost]
public ActionResult RunService(string operationType)
{
// Codes
Response.StatusCode = 200;
return Json(JsonRequestBehavior.AllowGet);
}
Hope this could help to you for how to make angular post to mvc controller. Thanks.
There is nothing special you have to do to get Angular to post to a standard MVC controller, and in fact I have several Angular/MVC apps that are using code almost identical to what you have above to POST to controllers that work fine.
I would use Firebug to confirm that your app is posting to the right place. One thing I noticed is that you might not want that trailing / at the end of your URL (so Home/Give instead of Home/Give/)
Good luck!

Call c# method from javascript for a redirect

I have a c# method for a redirect
[UIAuthentication()]
[UIMethod("cancelredirect", "mth"), UIMethodGroup("employeradmin")]
public void CancelRedirect(RequestContext Context)
{
Context.Redirect(string.Format("View.mth?EmployerID={0}", _employerID));
}
From this I have made a javascript function which is called if the cancel button on a form is pressed.
function getCancel() {
var confirmCancel = confirm('Are you sure you want to cancel?');
if(confirmCancel)
{
//redirect here
}
else
{
return false;
}
};
<input type="submit" id="Cancel" value="Cancel" name="Cancel" class="input_button" onclick="return getCancel();"/>
I was just wondering how would you call the c# method from the javascript to redirect to the page view.mth? I am not 100% sure how to do this as I have never done one one these before. Thanks for any help which you can give
Actually your question should be: "How to call action method from java-script?"
Assuming your controller class name: EmployeeController
if(confirmCancel)
{
document.location = = '/Employee/CancelRedirect';
}
Please go through following link for more info: How to redirect to another webpage in JavaScript/jQuery?
when you call server method by ajax, you can't do Redirect ,because the response handler is not the page.
If the purpose you call CancelRedirect just only to get one variable , the EmployerID from server side.
you can get EmployerID by Ajax and when the front side get the EmployerID , just redirect by :
window.location = "/View.mth?EmployerID=xxxx";
Ps: maybe you should make the ajax async property to false
try with ajax :
if(confirmCancel)
{
var url = '/Employee/CancelRedirect';
$.ajax({
url: url,
type: 'POST',
cache: false,
data :{ valeur : if you want to send a value }
})
}

Redirecting to another page in ASP.NET MVC using JavaScript/jQuery

I want to redirect from one page to another page in ASP.NET MVC 3.0 using JavaScript/jQuery/Ajax. On button click event I have written JavaScript code like below.
function foo(id)
{
$.post('/Branch/Details/' + id);
}
My controller code is like this:
public ViewResult Details(Guid id)
{
Branch branch = db.Branches.Single(b => b.Id == id);
return View(branch);
}
When I click on a button it is calling the Details action inside BranchController, but it doesn't return to the Details view.
I didn't get any error or exception. It's showing status 200 OK in Firebug. What is wrong in my code and how can I redirect to the Details view page?
You are not subscribing to any success callback in your $.post AJAX call. Meaning that the request is executed, but you do nothing with the results. If you want to do something useful with the results, try:
$.post('/Branch/Details/' + id, function(result) {
// Do something with the result like for example inject it into
// some placeholder and update the DOM.
// This obviously assumes that your controller action returns
// a partial view otherwise you will break your markup
});
On the other hand if you want to redirect, you absolutely do not need AJAX. You use AJAX only when you want to stay on the same page and update only a portion of it.
So if you only wanted to redirect the browser:
function foo(id) {
window.location.href = '/Branch/Details/' + id;
}
As a side note:
You should never be hardcoding urls like this. You should always be using url helpers when dealing with urls in an ASP.NET MVC application. So:
function foo(id) {
var url = '#Url.Action("Details", "Branch", new { id = "__id__" })';
window.location.href = url.replace('__id__', id);
}
This could be done by using a hidden variable in the view and then using that variable to post from the JavaScript code.
Here is my code in the view
#Html.Hidden("RedirectTo", Url.Action("ActionName", "ControllerName"));
Now you can use this in the JavaScript file as:
var url = $("#RedirectTo").val();
location.href = url;
It worked like a charm fro me. I hope it helps you too.
You can use:
window.location.href = '/Branch/Details/' + id;
But your Ajax code is incomplete without success or error functions.
// in the HTML code I used some razor
#Html.Hidden("RedirectTo", Url.Action("Action", "Controller"));
// now down in the script I do this
<script type="text/javascript">
var url = $("#RedirectTo").val();
$(document).ready(function () {
$.ajax({
dataType: 'json',
type: 'POST',
url: '/Controller/Action',
success: function (result) {
if (result.UserFriendlyErrMsg === 'Some Message') {
// display a prompt
alert("Message: " + result.UserFriendlyErrMsg);
// redirect us to the new page
location.href = url;
}
$('#friendlyMsg').html(result.UserFriendlyErrMsg);
}
});
</script>
<script type="text/javascript">
function lnkLogout_Confirm()
{
var bResponse = confirm('Are you sure you want to exit?');
if (bResponse === true) {
////console.log("lnkLogout_Confirm clciked.");
var url = '#Url.Action("Login", "Login")';
window.location.href = url;
}
return bResponse;
}
</script>
check the code below this will be helpful for you:
<script type="text/javascript">
window.opener.location.href = '#Url.Action("Action", "EventstController")', window.close();
</script>

update field or redirect page using jquery and asp.net mvc

Im new to jquery and stuck with what i want to achieve.
Heres what I want to do using jquery and asp.net mvc.
click a submit button
this calls an action method called LogOn in the controller Account
if the call allows users to log in succesfully redirect to a url (sepecified by LogOn)
if it fails replace a div(with id="error") with "sorry error occured"
so far I tried this:
$("#submit")
.button()
.click(function () {
$.ajax({
type: "POST",
url: "Account/LogOn",
dataType: "json",
success: function (data, textStatus) {
if (data.redirect) {
// data.redirect contains the string URL to redirect to
window.location.href = data.redirect;
}
else {
// data.form contains the HTML for the replacement form
$("#error2").replaceWith(data.error);
}
}
});
});
how do I construct the relevant bits in the action method? to make this work?
and is the jquery code ok? i suspect prob not.
Thanks
If you want to redirect asp.net page at same directory , you can by Jquery/Java script by this :
$("#ctl00_iframecontent_BtnCancle").click(function () {
window.location = "IncSLAList.aspx?bi=37";
});
and
To redirect to Another page of project , can use :
window.location.href = "http://ImageUpload/Welcome.aspx?
Your jQuery is almost correct:
Don't call .button() (unless you're using jQuery UI and want to do that)
Add return false; at the end of the click handler to prevent the browser from submitting normally.
In the action, you would either return Json(new { redirect = str }) or return Json(new { error = str }).

Categories