I have publish a new website where the website.pt/contact page is now at the website.pt#contact-us - how can change my actual controller's action to reflect this change?
public ActionResult Contact()
{
return View(); -> Index#contact-us
}
#contact-us is a URL location hash and has nothing to do with a View. Instead, try to redirect to that specific URL hash with return Redirect("website.pt#contact-us").
Related
I need to make my application open together with return a new window with another url
Below ASP.NET MVC code with what I plan to do.
Opens external url and then performs redirection to default system index.
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Details([Bind(Include = "AvisoId,Cliente,Data,Email,Telefone,Observacao,Enviado,Usuario")] Aviso aviso)
{
if (ModelState.IsValid)
{
db.Entry(aviso).State = EntityState.Modified;
db.SaveChanges();
Redirect("https://other-site-in-new-window.com");
return RedirectToAction("Index");
}
return View(aviso);
}
ASP.Net code runs on the web server, and so can't open another tab on the client browser. Because it's not in control of the client's browser - the web server's job is to the client what they request.
If you want to do something like this, you'll need to have a link on the webpage with target="_blank" for a new tab, and also use javascript to redirect the current page to wherever you want to go once the button is clicked.
Opening a new page on the browser is the client's responsibility not the server's (where your asp.net controller) runs.
What you could do however is return the url of the other page you want to open in a
TempData
ViewBag
ViewData
Cookie
Or possibly in any other form you see fit according to your application. Then on the client side, you retrieve the value of the url you want to open, and open it in a new tab.
Using your code and TempData
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Details([Bind(Include = "AvisoId,Cliente,Data,Email,Telefone,Observacao,Enviado,Usuario")] Aviso aviso)
{
if (ModelState.IsValid)
{
db.Entry(aviso).State = EntityState.Modified;
db.SaveChanges();
TempData["ExternalUrl"] = "https://other-site-in-new-window.com";
return RedirectToAction("Index");
}
return View(aviso);
}
Then in your cshtml page in javascript
...
let externalUrl = '#TempData["ExternalUrl"]';
if(externalUrl) {
//Do something here
}
...
I have an ASP.NET MVC app. My app is using T4MVC. In my controller, I need to redirect from one action to another. When I do this, I want to append a query string value. I can successfully redirect without the query string value, but I've been unsuccessful applying a query string value. My actions look like this:
[HttpPost]
[ValidateAntiForgeryToken]
public virtual ActionResult Action1()
{
return RedirectToAction(MVC.MyController.Action2().AddRouteValue("id", "5"));
}
[Route("action-2")]
public virtual ActionResult Action2(string input)
{
ViewBag.Input = input;
return View(viewModel);
}
The Action2 works fine when I visit ./action-2. I can also successfully POST to Action1. But, when the redirect doesn't work. I notice in the address bar the following:
/MyController/id
Why? How do I fix this? I just want to redirect back to Action2 but this time with a query string parameter added. What am I missing?
You need to specify the parameter by the name in the action (in this case "input") in order for it to work, see below:
return redirectToAction(MVC.MyController.Action2().AddRouteValue("input", "5"));
or alternatively:
return RedirectToAction("Action2", "MyController", new { input = "myInput"});
I try in following way and it works fine for me.
return RedirectToAction("Index", "CustomBuilder", new { usern = "admin" });
I am struggling to get my code work, but I think I've read enough to suggest this is the correct way to approach this.
On my intranet, I'd like the user to type in a single word to search into a textbox, and check a checkbox. When the new page loads, I'd like the URL rewritting services of ASP.NET MVC to kick in and change a value from
mysite.com/?id=blah&isChecked=true
to
mysite.com/home/index/blah/true
My code isn't working in the sense of it gives no error, but doesn't do what I am explaining. So, I've removed the check box to just focus on the textbox.
My only route is
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{MyType}",
defaults: new { controller = "Home", action = "Index", MyType = UrlParameter.Optional }
);
My Controller
public ActionResult Index()
{
ViewBag.Message = "Modify this";
return View();
}
[HttpGet]
public ActionResult Index(string MyType)
{
ViewBag.Message = "..." + MyType;
return View();
}
and my View has
#using (Html.BeginForm("Index", "Home",FormMethod.Get))
{
<input name="MyType" /><br />
<input type="submit" />
}
#Html.ActionLink("Click me", "Index", new { #MyType = "Blah" }) //renders correctly
The problem is, it shows the querystring still in the address bar
mysite.com/?MyType=MySearchValue
instead of
mysite.com/Home/Index/MySearchValue
You can't do this purely with routing because the browser will always send form values as query string parameters when they are part of a GET request. Once the request has been sent to the server, the MVC framework can't do anything about the URL that was used.
This leaves you with only one real option (assuming you don't want to send a custom request using JavaScript), which is to explicitly redirect to the desired URL (meaning you will always have two requests when this form is submitted).
The simplest way of doing this is simply in the controller (rather, in a separate controller to ensure that there is no conflict in method signatures):
public class FormController : Controller
{
public ActionResult Index(string MyType)
{
return RedirectToAction("Index", "MyProperController", new { MyType });
}
}
If you direct your form to this controller action, MVC will then use the routing engine to generate the proper URL for the real action and redirect the browser accordingly.
You could do this from the same controller action but it would involve inspecting the request URL to check whether a query string was used or not and redirecting back to the same action, which is a little odd.
I have a single controller and view working that calls a web service, and returns a result. At the moment, it's my default controller, called Home, and it uses the Index view page.
It's working. I can post data and then put something on the refreshed screen. It reloads the same view.
Now, once I submit, and I get a good reply, I want to load a different controller/view.
My routes look like this right now:
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
"Home",
"{lang}",
new { controller = "Home", action = "Index", lang="English" });
routes.MapRoute(
"Location",
"{lang}",
new { controller = "Location", action = "Index", lang = "English" });
I created a controlled called Location, and it just has this:
//LocationController
public class LocationController : Controller
{
public ActionResult Index()
{
return View();
}
}
In my home controller, I am doing the logic, and then attempting to load the new page.
[HttpPost]
public ActionResult Index(HomeModel model)
{
var proxy = new Proxy();
var r = proxy.GetLocationByAddress(model.SearchString, o.ToString());
if(r==null)
{
ViewBag.Error = "Error during search";
return View(model);
}
ViewBag.Error = string.Format("Found {0} at {1}, {2}", r.StreetName, r.Latitude, r.Longitude);
return RedirectToAction("Index", "Location");
}
But when I run it, submit it, step through, it hits the RedirectToAction - but ... the Home screen simply refreshes. I never see the new Location view. What am I doing wrong here? I have't grasped Routes yet... I need to pass a new object to the Location.Index screen to display...
Your route mapping is incorrect, check this out: http://www.asp.net/mvc/tutorials/controllers-and-routing/creating-custom-routes-cs
routes.MapRoute(
"Location",
"Location/{lang}",
new { controller = "Location", action = "Index", lang = "English" });
I don't think so you need to make any changes. As in your case you want to load different controller with its respecting view you need below change only
replace this code return RedirectToAction("Index", "Location");
with this code return Redirect("http://www.yoursite.com/Location/Index");
Your change is like redirection from one page to another therefore you need to put your complete path here
please try & reply if any problem
I'm working with ASP.net and MVC3 . I need to show a popup or go to the login page When the session get expired. Can any one please tell me How to redirect to login page which is having action name as "index" and the controller name as "Home".
My Code is:
This method is in my model.In this model I have to redirect to login page.
protected Product GetCurrentCorp(HttpContextBase context)
{
if (context.Session != null)
{
var selectedProduct = context.Session["SelectedProduct"];
if (selectedProduct != null)
{
var product= selectedProduct as Product;
return product;
}
}
// Here I need to redirect to index page(login page)
throw new ArgumentException("Product is not set, Cannot Continue.");
}
If LoggedOn is your Action and Account is your Controller then you can write your code as:
return RedirectToAction("LoggedOn", "Account");
Hope this will help you.!!!
Use
Redirect
or RedirectToAction
or RedirectToRoute
Also refer old post ASP.Net MVC Redirect To A Different View
This is the self contained action that is showing you examples of redirection to different action or URL.
public ActionResult MyAction()
{
// Use this for action, can also be used to redirect
// to action on different controller by adding parameter
return RedirectToAction("MyActionName");
// Use this for URL
return Redirect("http://example.com/foo/bar");
}
Hope this is of help to you.
You can use RedirectToAction()
return RedirectToAction("ActionName", "ControllerName");