Rakesh Jogani
Rakesh Jogani

Reputation: 93

Get Attribute from URL in ASP.NET MVC View

I have url like below

http://ixorra.com/products/27/13

I want 27 value in view

My URL Routing config like :

routes.MapRoute(
            name: "Default",
            url: "{controller}/{action}/{id}",
            defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional },
            namespaces: new[] { "IxorraExports.Controllers" }
        );

Any idea how to get a value of 27 in view.

Upvotes: 0

Views: 492

Answers (2)

David
David

Reputation: 218827

Based on your comments on the question above:

In URL "Products" is Action method name and 27 is my first parameter of action method and 13 is the second parameter of action method.
Controller name is home and "Home" is default controller in Route configuration.

First of all, your URL is wrong. You forgot the controller. It should be:

http://ixorra.com/home/products/27/13

Once you've corrected that, you'll just need to add another optional parameter to your route configuration. This would only change these lines:

url: "{controller}/{action}/{id}/{foo}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional, foo = UrlParameter.Optional },

Naturally, you'll want to use a more meaningful name than foo. But we don't know what these values mean, so that's just a placeholder for now.

Your controller action can then accept those URL parameters:

public ActionResult Products(int id, int foo)
{
    // your action method
}

(This is where the more meaningful name becomes, well, meaningful. Whatever common generic name would make sense for that second parameter is what you'd use both in the route definition and in the method definition.)

At this point you have the value, so you can do whatever you like with it. Add it to the model that gets sent to the view, send it in the ViewBag, etc. For example:

public ActionResult Products(int id, int foo)
{
    ViewBag.foo = foo;
    return View();
}

Then in your view you can access the value from the ViewBag:

<span>The value is: @ViewBag.foo</span>

Upvotes: 1

Shahrzad Jahanbaz
Shahrzad Jahanbaz

Reputation: 108

You can do it by split the url:

var url = $(location).attr('href');
var parts = url.split("/");
alert(parts[0]);

you can desired part usinf proper index. I hope it can help!

Upvotes: 0

Related Questions