How can I redirect the viewer to a URL?
I noticed that someone asked How to redirect to another webpage in JavaScript/jQuery?, but I'm not exactly sure where this should go.
I have tried in the controller with:
window.location.replace("http://192.168.1.109/MWT/Taglist/ShowMap" + LastId);
and in the view with:
<% if (BreakCount >= 8) {
var url = "http://192.168.1.109/MWT/Taglist/ShowMap" + LastId;
window.location.replace(url);
} %>
Neither of these work. In both places places window has a red squiggly line underneath it and when I hover over it the message says "The name 'window' does not exist in the current context."
Any help would be greatly appreciated!
=D
Your question is tagged MVC 3, so I'll give you the answer for that in spite of the JavaScript example you listed. In your controller class use this code:
public ActionResult MyAction()
{
// Use this for an action
return RedirectToAction("ActionName");
// Use this for a URL
return Redirect("http://192.168.1.109/MWT/Taglist/ShowMap" + LastId);
}
This is occuring on the server, meaning that the client browser recieves a redirect response for which the browser will likely submit an additional request. If you return a page with JavaScript it will have to load a page, run the JavaScript (presuming it is enable on the client's browser), the load the next page. Among other problems, using JavaScript means that if the user presses the back button they will be repeatedly redirected again back to the page they are currently on.
Inside your controller call return RedirectToAction().
public ActionResult MyAction() {
return RedirectToAction("Index", "Home");
}
or, it you use T4MVC (and you should ;-))
public ActionResult MyAction() {
return RedirectToAction(MVC.Home.Index());
}
Do not put the if statement in the view - that's not the MVC way. It is the responsibility of the controller to decide whether to redirect to a different view.
Try like this:
<script type="text/javascript">
// Make sure the LastId variable is defined
var LastId = '123';
<% if (BreakCount >= 8) { %>
var url = "http://192.168.1.109/MWT/Taglist/ShowMap" + LastId;
window.location.replace(url);
<% } %>
</script>
Try this:
<script type="text/javascript">
var id = '123';
location.href = "http://192.168.1.109/MWT/Taglist/ShowMap/" + id;
</script>
Try like this :
top.location.href = "/url";
Related
sorry for asking this question ..i am working on a Cakephp 2.x ... i have a view page in my controller name folder e.g Controller/index.ctp ... and i have ajaxfiles are stored in app/webroot/ajax/ajaxfile.html
now on my index.php file i am acessing the ajax page like this
<a href="ajax-demo/ajaxfile.html" class="file-link">
<span class="icon file-png"></span>
Simple gallery</a>
Controller
public function index(){
}
now the problem is i want to send the variables to both of my pages ... index.ctp and ajaxfile ... how can i do this ??what is the best approach to tackle these things ....
do i have to move the ajaxfiles from webroot and paste under the controller name folder?
if is it so then how can i send variables to ajax files which has no model and controller
please if any one know the solution then please advice me. and give an example too
There are different way to achieve this, here I'm writing the simplest one
First you need to move your "index.ctp" file to your "View/YOUR CONTROLLER NAME/" folder.
1) To access the variable in view you need to set it from your controller's method like this
public index(){
$this->set('yourVariable', 'Your Value');
}
2) To access the value in your view file (index.ctp), you need to call this variable like this
$yourVariable;//If you want to print this then you can write like this
echo $yourVariable;
3) To call a ajax file from your index.ctp the simplest method is to call a onclick event on this anchor, the onclick event will call a JAVASCRIPT method which will further make a ajax call and will place the output in an element in your index.ctp, The ajax call will further call your controller method (implement your html related logic here)
For example,
<span class="icon file-png"></span>Simple gallery
<div id="yourAjaxFileOutputReplaceMentDiv"></div>
4) create a javascript method in your JS file, this JS file must be loaded in your layout file.
function yourAjaxCallMethod(BaseURL,yourVarible)
{
//Initialize Ajax Method
var req = getXMLHTTP();//Let's this method Initialize your Ajax
if (req)
{
req.onreadystatechange = function() {
if (req.readyState == 4)
{
if (req.status == 200)
{
document.getElementById('yourAjaxFileOutputReplaceMentDiv').innerHTML=req.responseText;
} else {
alert("There was a problem while using XMLHTTP:\n" + req.statusText);
}
}
}
var URL = BaseURL+yourVarible+'/'+Math.random();
req.open("GET", URL, true);
req.send(null);
}
}
5) Your AJAX file related method in your controller "yourController". Set autoRender to False
public function ajaxMethod(){
$this->autoRender = false;
//Check $this->request['pass'] for arguments send from ajax call
$retreivedVariable = $this->request['pass'][0];
echo 'I retrieved variable'.$retreivedVariable;
}
However instead of writing core javascript and ajax method you can call the inbuild Ajax Helper for same.
I am developing application using Ajax and jsp.
My index.jsp page has HTML code for Login and some Ajax code in javascript. Ajax will call my another CheckLogin.jsp page
CheckLogin.jsp page checks on server for valid username and password. It returns "success" if it's valid otherwise will return message stating "username or password is not valid."
Now, when username and passwrod is valid, instead of success, I want to redirect the page to "Home.jsp" what should I do?
I am new to jsp. I appreciate your help on this.
JSP code gets run once on the server before it goes to the client, so JSP/JSTL cannot do a redirect following the success or otherwise of an AJAX call (without a full page refresh - which obviates the use of AJAX). You should to do the redirect with Javascript:
if (success) {
var successUrl = "Home.jsp"; // might be a good idea to return this URL in the successful AJAX call
window.location.href = successUrl;
}
On successful AJAX call/validation, the browser window will reload with the new URL (effectively a redirect).
Since I don't see your code, you can integrate this somewhere inside your validation :
<%
pageContext.forward("logged.jsp");
%>
function Edit() {
var allVals = $('#NEWFORMCampaignID').val();
if (allVals > 0) {
window.location = '/SMS/PrepareSMS?id='+allVals;
}
else
alert("Invalid campaign to Edit")
}
In order to redirect using Button click and pass some parameters, you can call the Controller Path(#RequestMapping(value="/SMS/PrepareSMS")) and then handle it there..
Can anyone help me with, I am trying to create a download counter to my website.
I have a ajax script that counts up by 1 when the users clicks the download link, the issue I am having is on some browsers it goes to the download link before completing the ajax count script.
Is there a way that I can redirect to the download file once the script has completed. At the moment I have as follows
This is the link :-
<a href='downloads/".$downfile."' onclick=\"Counter('$referid');\"'>Download File</a>
This is the counter script:-
<script type="text/javascript">
function Counter(id)
{
$.get("clickcounter.php?id="+id);
{
return false;
}
}
</script>
This is the php script (clickcounter.php)
<?php
include('dbutils.php');
$referid = $_GET['id'];
$q = "SELECT * FROM downloads WHERE downid =".$referid;
$r = mysql_query($q);
while ($row = mysql_fetch_array($r))
{
$click = stripslashes(trim($row['downcount']));
$download = $row['downfile'];
}
$countup = $click + 1;
$qUpdate = "UPDATE downloads
SET downcount=$countup
WHERE downid=$referid";
$rUpdate = mysql_query($qUpdate);
?>
A few relatively small modifications should solve the problem. First, change the onclick to the following:
onclick=\"Counter('$referid', this); return false;\"
What we have done is to send in this as the second argument to the Counter function so we have a reference to the clicked link. Secondly, we have added return false, which blocks the browser from navigating to the url specified in the href.
The modified counter function looks like this:
function Counter(id, link) {
$.get("clickcounter.php?id=" + id, function() {
location.href = $(link).attr("href");
});
}
We now have a reference to the clicked link. A function has now been specified as the second argument to $.get(). This is the success-function, which is called when the ajax call has been successfully called. Inside that function we now redirect to the url specified in the href attribute on the clicked link.
I feel I should point out that the recommended way is to bind the onclick using jQuery separate from the html. The referid can be stored in a data attribute (which I chose to call data-rid):
<a href='downloads/".$downfile."' class='dl' data-rid='$referid'>Download File</a>
Then you bind the onclick for all download links (a elements with a "dl" class):
$(function() {
$("a.dl").click(function() {
var id = $(this).attr("data-rid");
var href = $(this).attr("href");
$.get("clickcounter.php?id=" + id, function() {
location.href = href;
});
return false;
});
});
(I feel I should point out that the code has not been tested, so it's possible that a typo has snuck in somewhere)
I'm using Fancybox 1.3.4 with ASP.NET MVC 3.
I have following link :
<a id="various" href="Like/List/#feed.Id" class="petlikeCount liked">#feed.LikeCount</a>
and also jquery :
<script type="text/javascript">
$(document).ready(function () {
$("#various").fancybox({
type: 'ajax'
});
});
</script>
Controller action in Like controller :
public JsonResult List(int id)
{
return Json("success", JsonRequestBehavior.AllowGet);
}
My problem is that Like/List is never called (checked with the breakpoint) and fancybox just appears and show content of "parent" page....
I also tried with iframe content returning pure html back, but I'm getting same strange behavior as above.
Thank you in advance!
I'd recommend you using HTML helpers instead of hardcoding anchors:
#Html.ActionLink(
feed.LikeCount,
"List",
"Like",
new { id = feed.Id },
new { id = "various", #class = "petlikeCount liked" }
)
Another thing that you should make sure is that the feed.Id is actually an integer variable so that when the List action is invoked it is correctly passed this id.
So your url should look something like this: /List/Like/123. And then assuming tat you have kept the default route and haven't messed up with some custom routes, the List action should be called and passed the correct id as argument.
Also I would very strongly recommend you using a javascript debugging tool in your browser such as FireBug in which you will be able to see any potential errors with your scripts as well as the actual AJAX requests being sent which will allow you to more easily debug such problems.
My first post...
When I use RedirectToAction the url in the browser doesn't change. How can I achieve this?
I'm switching over to ASP.NET MVC 3.0 (also using jQuery Mobile) after 10+ years using web forms. I'm about 8 weeks into it, and after several books and scouring Google for an answer, I'm coming up dry.
I have a single route defined in Global.asax:
routes.MapRoute(
"Routes",
"{controller}/{action}/{id}",
new { controller = "Shopping", action = "Index", id = UrlParameter.Optional }
I have a ShoppingController with these actions:
public ActionResult Cart() {...}
public ActionResult Products(string externalId) {...}
[HttpPost]
public ActionResult Products(List<ProductModel> productModels)
{
// do stuff
return RedirectToAction("Cart");
}
The url when I do a get and post (with the post having the RedirectToAction) is always:
/Shopping/Products?ExternalId=GenAdmin
After the post and RedirectToAction I want the url in the browser to change to:
/Shopping/Cart
I've tried Redirect, and RedirectToRoute but get the same results.
Any help would be greatly appreciated.
[Update]
I found that jQuery Mobile AJAX posts are the culprit here. If I turn off jQuery Mobile's AJAX it works.
<script type="text/javascript" src="http://code.jquery.com/jquery-1.6.4.min.js"></script>
<script type="text/javascript">
// do not handle links via ajax by default
$(document).bind("mobileinit", function () { $.mobile.ajaxEnabled = false; });
</script>
<link rel="stylesheet" href="http://code.jquery.com/mobile/1.0rc2/jquery.mobile-1.0rc2.min.css" />
The ordering of the above scripts is important. I had to include the script to jQuery first, then include the script to disable jQuery Mobile's use of AJAX and then include the script to jQuery Mobile.
I'd still like to find a way to use AJAX and have the url update properly. Or at the least be able to call jQuery Mobile's "loading" message (or bake my own).
I think I've found an answer. Buried deep in the jQuery Mobile documentation, there is information about setting the data-url on the div with data-role="page". When I do this, I get the nice jQuery Mobile AJAX stuff (page loading message, page transitions) AND I get the url in the browser updated correctly.
Essentially, this is how I'm doing it...
[HttpPost]
public ActionResult Products(...)
{
// ... add products to cart
TempData["DataUrl"] = "data-url=\"/Cart\"";
return RedirectToAction("Index", "Cart");
}
Then on my layout page I have this....
<div data-role="page" data-theme="c" #TempData["DataUrl"]>
On my HttpPost actions I now set the TempData["DataUrl"] so for those pages it gets set and is populated on the layout page. "Get" actions don't set the TempData["DataUrl"] so it doesn't get populated on the layout page in those situtations.
The only thing that doesn't quite work with this, is when you right-click... view source... in the browser, the html isn't always for the page you are on, which isn't unusual for AJAX.
Not sure if it is still actual, but in my case I wrote following helper method
public static IHtmlString GetPageUrl<TModel>(this HtmlHelper<TModel> htmlHelper, ViewContext viewContext)
{
StringBuilder urlBuilder = new StringBuilder();
urlBuilder.Append("data-url='");
urlBuilder.Append(viewContext.HttpContext.Request.Url.GetComponents(UriComponents.PathAndQuery, UriFormat.UriEscaped));
urlBuilder.Append("'");
return htmlHelper.Raw(urlBuilder.ToString());
}
And then use it as follows:
<div data-role="page" data-theme="d" #Html.GetPageUrl(ViewContext) >
This way I don't need for every redirect action store a TempData. Worked for me fine both for Redirect and RedirectToAction. This would not work properly in case if you use method "View()" inside controller and return different view name, which will change UI, but will retain url.
Hope it helps
Artem
David, this was a big help to me. I just wanted to add that in my case I had to use the following format to get the Url to display in the correct form as my other url's:
TempData["DataUrl"] = "data-url=/appName/controller/action";
return RedirectToAction("action", "controller");
As a side note, I also found that when assigning the value to TempData["DataUrl"] I was able to leave out the escaped quotes and enter it exactly as above and it seems to be working fine for me. Thanks again for your help.
There is an issue on github
https://github.com/jquery/jquery-mobile/issues/1571
It has a nice solution without the need of TempData