add querystring parameter in URL - asp.net-mvc

I am using asp.net mvc.
here I am not asking on controller logic but at view page.And I am not messing with default setting of url routing.
I have a view having some url like /controller/action?CID=2
In this view I want to put Link having above structure but with different controller.
The point is get the current url parameter and put hyperlink with same Querystring parameter.

<%=Html.ActionLink("linkText", "actionName",
"controllerName", new {CID = Request.QueryString["CID"]}, null) %>
Do you mean something like this?

Related

Razor Url.Action adding site folder path into Url

I have an MVC project that lives on server in /root/folder1/, and a domain name pointing there.
So the url, www.site.com/Home is working fine.
However, all my #Html.ActionLinks and #Url.Action, etc. are rendering as www.site.com/folder1/Home
The links still work, but it is ugly, and I don't want the folder name to be known.
Anyone know why it's doing this and how to stop it?
You should be using something like this for your ActionLinks
#Html.ActionLink("Link Text", "ActionName", "ControllerName") 'NOTE YOU DO NOT NEED TO INCLUDE THE Controller part of the controller name. So for say AdminController you could simply set the controllerName in the ActionLink to `Admin`
You can also setup your ActionLinks like the below if you have to pass an Id or other value to the controller.
#Html.ActionLink("Link Text", "ActionName", "ControllerName", New With {.YourVariableName = "SomeValue"})
If you need to specify and HTML attribute for the control being rendered you can set those with one more overload.
#Html.ActionLink("Link Text", "ActionName", "ControllerName", New With {.YourVariableName = "SomeValue"}, New With {.htmlAttributeName = ""})
If you need to Specify the HTML attribute without a need to pass a value to the controller you can simply replace New With{.YourVariableName = "SomeValue"}withNothing`
Hope this works or at least points you in the right direction. A fresh MVC project out of the box has a Controllers folder. Which means server path looks something like root/controllerFolder/controller/action using the above works fine for me and only produces Url's that follow the standard {controller}/{action}/{id}. Say I have a need to call an Edit Action inside the AdminController which needs an ID so it knows what record I want to edit and I also want to add a class to this button so I can style it or anything else. I would do this
#Html.ActionLink("Edit", "Edit", "Admin", NEW WITH {.ID = #currItem.Id}, NEW WITH{.Class = "MyButtonClass"})
The URL that is generated will look like this
www.mysite.com/Admin/Edit/2
maybe this is a little more than you needed but your question appears to actually follow the standard {controller}/{action}/{id}. Just in-case I am missing something I figured I would try to at least point you in the right direction.

Pass relative URL ASP.NET MVC3

I'm trying to pass a list of URL's with Id attributes from a controller to a view.
I can pass a <a href=...> link back but I don't think writing a 'localhost' absolute path is a clean way of approaching this. I cant pass an ActionLink back as it returns the full string. Is ther a simple solution to this problem? Thanks in advance.
Using this overload of the UrlHelper.Action() method and Request object you can get a complete URL including the route parameters such as IDs and the actual hostname of the application.
string url = Url.Action("action", "controller",
new System.Web.Routing.RouteValueDictionary(new { id = id }),
"http", Request.Url.Host);
UrlHelper is available in the controller via its Url property.
You can then pass such URL into your view.
It is also possible to use UrlHelper directly inside your view to create URLs for controller actions. Depends if you really need to create them inside the controller.
Edit in response to comments:
Wherever you need to place the URLs, this "URL builder" you are looking for is still the UrlHelper. You just need to pass it (or the generated URLs) where you need it, being it inside the controller, view or custom helper.
To get the links inside the unsorted list HTML structure you mention, you need to put anchors inside the list items like this:
<ul>
<li>Link</li>
...
</ul>
Then again you just need to get the URLs from somewhere and that would be from UrlHelper.
Simple and easy.
text
the route id = the parameter that is going to be inserted into your method.
eg.
function Details(int id) {
//id has the value of my_var_id
}

ASP.Net MVC redirecttoaction not passing action name in url

I have a simple create action to receive post form data, save to db and redirect to list view.
The problem is, after redirecttoaction result excutes, the url on my browser lost the action section. Which it should be "http://{hotsname}/Product/List" but comes out as "http://{hotsname}/Product/".
Below is my code:
[HttpPost]
public ActionResult Create(VEmployee model, FormCollection fc)
{
var facility = FacilityFactory.GetEmployeeFacility();
var avatar = Request.Files["Avatar"].InputStream;
var newModel = facility.Save(model, avatar);
return RedirectToAction("List");
}
The page can correctly render list view content, but since some links in this view page use relative url, the functions are interrupted. I am now using return Redirect("/Employee/List") to force the url. But I just wonder why the action name is missing. I use MVC3 and .Net framwork 4.
I am new to ASP.Net MVC, thanks for help.
Your route table definitely says that "List" action is default, so when you redirect to it as RedirectToAction("List") - routing ommits the action because it is default.
Now if you remove the default value from your routes - RedirectToAction will produce a correct (for your case) Url, but you'll have to double check elsewhere that you are not relying on List being a default action.
Well, Chris,
If you get the right content on http://{hotsname}/Product/ then it seems that routing make that URL point to List either indirectly (using pattern like {controller}/{action}) and something wrong happens when resolving URL from route or {action} parameter is just set wth default value List. Both URLs can point to the same action but the routing engine somehow takes the route without explicit action name.
You should check:
Order in which you define your routes
How many routes can possibly lead to EmployeeController.List()
Which one of those routes has the most priority
Default values for your routes
Just make the route with explicit values: employee/list to point to your List action and make sure that is the route to select when generating links (it should be most specific route if possible).
It would be nice if you provide your routes mappings here.
but since some links in this view
page use relative url, the functions
are interrupted.
Why do you make it that way? Why not generate all the links through routing engine?
When using the overload RedirectToAction("Action") you need to be specifying an action that is in the same controller. Since you are calling an action in a different controller, you need to specify the action with the alternate overload e.g. RedirectToAction("List", "Employee").

ASP.NET MVC create absolute url from c# code

How do i generate an absolute url from the c# code?
I want to generate a url like this: localhost/{controller}/{action}/{id}. Is there a way to do it in c# like how it can be done in the views?
It wont be generated inside the controller but inside a ViewModel.
string absUrl = Url.Action("Index", "Products", null, Request.Url.Scheme);
Just add Request.Url.Scheme. What this does is add a protocol to the url which forces it to generate an absolute URL.
Check out a similar question Using html actionlink and URL action from inside controller. Seems to be similar and reusable for your requirements.
If you don't want to "build" the url and just want the full path of the current page, this will do the trick
Context.Server.UrlEncode(Context.Request.Url.AbsoluteUri)
I know it's not as elegant as an Extension Method but thought of sharing it for educational purposes
As of latest update to MVC you can use below overload for Url.Action
string url=Url.Action("ActionName", "Controller",
new RouteValueDictionary(new { id= someid }),
//url param
HttpContext.Request.Url.Scheme,
HttpContext.Request.Url.Host);
which generates
http://localhost:port/Controller/ActionName?id=someid

How can I implement Dynamic Routing with my choice of URL format?

My URL requirement is countryname/statename/cityname. For this I'm writing my own RouteHandler and adding one new route into the routecollection like this:
routes.Add(new Route("{*data}",
new RouteValueDictionary(new
{
controller = "Location",
action = "GetLocations"
}),
new MyRoutehandler()));
Now my question is: How do I generate this type of URL?
I tried Html.ActionLink() but it's asking for an action name and controller name. However, in my URL format I don't have any action name or controller name. How do I solve this?
Is there a reason you can't just use the following with the built-in route handler:
routes.MapRoute("LocationRoute",
"{countryname}/{statename}/{cityname}",
new { controller = "Location", action = "GetLocations" });
That may conflict with the default "{controller}/{action}/{id}" route, but that would happen with your current system anyway (unless you make a custom Route, inheriting from System.Web.Routing.RouteBase, rather than a custom Route Handler). The Route Handler is for handling what to do AFTER the route data has been extracted. Since you're still using Controller and Action, you should still be able to use the MvcRouteHandler. If you want to customize how the Route Data is extracted, you probably want a custom Route.
Btw, if you want to use a route which doesn't involve Controller and Action names, use Html.RouteLink. ActionLink is just a wrapper which puts the controller and action into the RouteValuesDictionary and calls the same internal helper as RouteLink.
Although in this case, the route still has a Controller and Action ("Location" and "GetLocations"), so you can still use ActionLink. I think ActionLink lets you specify a Route Name, so if you give your route a name you can specify that name in ActionLink and it will use that route to generate the URL (I may be wrong about that and if so you can still use RouteLink and manually add the controller and action route values)

Resources