How do I get parameter value from the URL in the client side, view?
URL:
localhost:18652/category/1
MapRoute:
routes.MapRoute(
name: "ResultsByCategory",
url: "category/{id}",
defaults: new { controller = "Home", action = "ResultsByCategory"}
);
How do I get ID?
I tested this url:
http://localhost:1865/category/Index/1
In view I have this:
You can get id by this code in example view:
#{
var id = Request.Url.Segments[3];
}
In general case, You can use this code:
#{
var id = Request.Url.Segments.Last();
}
Didn't understand the point of directly getting from URL, Request as your view is always going to get loaded from your controller.
So as derloopkat suggested
In your Home Controller
Public ActionResult ResultsByCategory (int id)
{
ViewBag.id = id;
return View();
}
In your view you can use it by calling
#ViewBag.id
This code works better for your code
string id = Request.Path.Value.Split('/').LastOrDefault();
Related
net MVC 4 I followed the microsoft tutorials on how to pass a parameter to a controller from a cshtml view in mvc and I keep getting an error that says the resource cannot be found.If I put a break point in the cshtml I can actually see the value of the Id but it is not hitting the controller at all seems like it cant find it
Description: HTTP 404. The resource you are looking for (or one of its dependencies) could have been removed, had its name
changed, or is temporarily unavailable. Please review the following
URL and make sure that it is spelled correctly.
Requested URL: /UploadLogs/DisplayUploadedFileContents/89
This is my controller method
public class DisplayUploadedFileController : Controller
{
private MarketingDBEntitiesModel db = new MarketingDBEntitiesModel();
// GET: DisplayUploadedFile
public ActionResult DisplayUploadedFileContents(int UploadId)
{
return View(db.marketingdbclients_dataTable.OrderByDescending(r => r.ClientId).Where(r => r.ClientDataId < 1000).ToList());
// return View();.
}
}
My line in the cshtml
<td>
#*#Html.ActionLink("Details", "Details", new { id = item.UploadId })*#
#Html.ActionLink("Details", "DisplayUploadedFileContents", new { id = item.UploadId })
</td>
My route config
routes.MapRoute(
name: "DisplayUploadedFileContents",
//url: "",
url: "{controller}/{action}/{id}",
defaults: new { controller = "DisplayUploadedFile", action = "DisplayUploadedFileContents", id = UrlParameter.Optional });
Making a couple of changes should get this working.
First, if you want to use the routing for the url like this {controller}/{action}/{id}, change the parameter name in the controller action from UploadId to id:
public ActionResult DisplayUploadedFileContents(int id)
Next, it looks like you're linking from a different controller since in the error the requested URL is /UploadLogs/DisplayUploadedFileContents/89 (note UploadLogs is not DisplayUploadedFile).
Linking to the DisplayUploadedFile controller from a view that belongs to a different controller, you will need to use this overload taking 5 parameters:
#Html.ActionLink("Display File Contents", "DisplayUploadedFileContents", "DisplayUploadedFile",
null, new { id = item.UploadId })
However, if you're accessing the controller from a view within the same controller you should be able to use this overload for ActionLink taking 3 parameters:
#Html.ActionLink("Display File Contents", "DisplayUploadedFileContents", new { id = item.UploadId })
Please refer to the ActionLink documentation
url: "{controller}/{action}/{id}
You didn't respect the routing configuration. Try:
#Html.ActionLink("DisplayUploadedFile", "DisplayUploadedFileContents", new { UploadId = item.UploadId })
#Html.ActionLink("DisplayUploadedFile", "DisplayUploadedFileContents", new { UploadId = item.UploadId}, null )
You need the Argument for "htmlArgument"
Please Refer to: HTML.ActionLink method
I have a problem in my MVC project were the first time I request a page it makes a redirection to another area, but the second time I request it works correctly.
The url I use is: http://localhost:2012/pt/Documentation/Index and redirects me to http://localhost:2012/es/Services/Documentation
I've debugged the code and in both requests the url asked for is the first, and the action that respond the request is correct, but once the reply gets to the browser , the first time is recieved with a 302 code and it redirects me to this second URL.
I've checked the web.config with any redirection rule but there aren't.
The Area registration is:
routes.MapRoute(
name: "Default",
url: "{language}/{controller}/{action}/{id}",
defaults: new { language = "es", controller = "Home", action = "Index", id = UrlParameter.Optional }
);
And the controller is like:
public class DocumentationController : Controller
{
public ActionResult Index(string language)
{
return View();
}
}
The setCulture is an atribute that is used to change the translations needed in the view.
I've tried to comment the view and the layout but it still redirects without code.
Any help will be aprecciated.
****EDIT****
First request:
Second request:
The view code is:
#model string
#{
ViewBag.Title = "Resend documentation";
Layout = null;
}
I'm teaching myself MVC and have an issue with routing correctly
I have a controller named "ClipsController" and 1 view inside with the name "Index" (boring, i know)
I have my routeconfig file configured with the following route:
routes.MapRoute(
"Clips",
"Clips/{id}",
new { controller = "Clips", action = "Index", id = urlparameters.Optional }
);
which is Before the "Default" route. When i go to /Clips/ExampleID
it does hit the correct route, and does start the Index action in the Clips controller. What i'm having trouble with is the parameter 'ID' fails to pass through into the Index page, but i end up on the index action of the Clips controller, with the URL domain.my/Clips/ExampleID
I attempt to get the ID parameter with
httpcontext.current.request.querystring["id"]
which always returns a null. My actionresult in the controller is as follows:
public ActionResult Index(string id)
{
return view()
}
To reiterate, I'm not able to see the querystring id on the index view, even though the URL does the correct route, and the actionresult in the controller is to my kowledge correct. If i have done something critically wrong or you need more information please let me know, Thanks.
I attempt to get the ID parameter with
httpcontext.current.request.querystring["id"]
No, you don't have any query string parameters in this url:
http://domain.my/Clips/ExampleID
Query string parameters follow the ? character in an url. For example if you had the following url:
http://domain.my/Clips?id=ExampleID
then you could attempt to read the id query string parameter using your initial code.
With this url: http://domain.my/Clips/ExampleID you could query the id route value parameter. But using HttpContext.Current is absolutely the wrong way to do it. You should never use HttpContext.Current in an ASP.NET MVC application. Quite on the contrary, you can access this information everywhere where you have access to HttpContextBase (which is pretty much everywhere in the ASP.NET MVC application pipeline):
httpContext.Request.RequestContext.RouteData.Values["id"]
Long story short, if you needed to query the value of this parameter inside your controller action you would simply use the provided id argument:
public ActionResult Index(string id)
{
// Here the id argument will map to ExampleID
return view()
}
Also you probably don't need your custom route:
routes.MapRoute(
"Clips",
"Clips/{id}",
new { controller = "Clips", action = "Index", id = urlparameters.Optional }
);
That's completely redundant and it is already covered by the default route:
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
So feel more than free to get rid of your custom route.
Basically, in my controller I'm redirecting to the Index action:
return RedirectToAction("", new { id = id });
This works great except for the fact that the URL bar displays controllername/index/id. I would like to be able to avoid displaying "Index" in the URL. Is this possible? And if so, how?
Add a route without the action name in your global.asax.cs:
routes.MapRoute("NoActionInURL", "ControllerName/{id}",
new { controller = "ControllerName", action = "Index", id = UrlParameter.Optional });
I'm using ASP.NET MVC 4 C Sharp and I have this error
Server Error in '/' Application.
The resource cannot be found. Description: HTTP 404. The resource you
are looking for (or one of its dependencies) could have been removed,
had its name changed, or is temporarily unavailable. Please review
the following URL and make sure that it is spelled correctly.
Requested URL: /ClerkBooking/ConfirmBooking/22
In my controller I have:
[HttpPost]
[ValidateAntiForgeryToken]
[Authorize(Roles = "Booking Clerk")]
public ActionResult ConfirmBooking(int id = 0)
{
if (ModelState.IsValid)
{
//Find the booking
Booking booking = db.Bookings.Find(id);
//Get RoomID of Preferred Room.
int roomId = Convert.ToInt32(db.Rooms.Find(booking.PreferredRoom));
//Set RoomID of Booking.
booking.RoomId = roomId;
//Save Changes.
db.SaveChanges();
}
return View("Index");
}
So im not sure why its not finding the method even though its in the correct place. Any help would be great! Thanks!
Your action link #Html.ActionLink("Confirm Booking", "ConfirmBooking", new {id = booking.BookingId}) is going to make a GET request, but you put an [HttpPost] attribute on the action.
You'll probably want to make the link a button inside of a form post instead of an action link.
Here's an example:
#using (Html.BeginForm("ConfirmBooking", "ClerkBooking", new { id = booking.BookingId }))
{
<input type="submit" value="Confirm Booking" />
}
Make sure your controller is called "ClerkBooking" and remove the [HttpPost] decoration from the method.
Are adding your AntiForgeryToken to your html file?
#using (Html.BeginForm("Manage", "Account")) {
#Html.AntiForgeryToken()
}
If not then probably asp.net mvc is blocking to reach your controller.
Also do not forget to check your Global.asax with the parameters:
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
"Default", // Route name
"{controller}/{action}/{id}", // URL with parameters
new { controller = "ClerkBooking", action = "ConfirmBooking", id = UrlParameter.Optional } // Parameter defaults
);
}
Otherwise you have to declare your id object from outside.
$.ajax("/ClerkBooking/ConfirmBooking/?id=22", {
type: "POST",
contentType: "application/json; charset=utf-8",
success: function (result) {
//Do Something
}
}
}).fail(function () {
//Do Something
});