orbit
orbit

Reputation: 1296

How to display customized URL through Routeconfig

I have an action link in HTML.

<a href="@Url.Action("UserWisedPost", "Blog", new { userName = item.UserName,userId=item.UserId })">@item.UserName</a>

In controller,

public ActionResult UserWisedPost(string userId,string userName, int? page, int pageSize = 10)
{
     page = page == null || page == 0 ? 1 : page;
     var model = _post.GetByUserId(userId).ToPagedList((int)page, pageSize); 
     return View(model);
}

And in RouteConfig

routes.MapRoute(
                name: "userwisedPost",
                url: "{controller}/{action}/{userName}",
                defaults: new { controller = "Blog", action = "UserWisedPost", userName=UrlParameter.Optional}
            );

You have probably understood what I want to mean. I want to display URL like ../UserWisedPost/userName but want access data by userId in controller.

How can I do that?

Upvotes: 1

Views: 449

Answers (2)

Mihail Stancescu
Mihail Stancescu

Reputation: 4138

If you want to have the userId other than query string you should add a form and put it as a hidden field.

Or, you can use AJAX to post the data:

<a href="postUserWised(@Url.Action("UserWisedPost", "Blog"), @item.UserName,@item.UserId)">@item.UserName</a>

Then in your scripts section in that view:

@section scripts {
<script type="text/javascript">
   function postUserWised( url, userName, userId) {
      $.ajax({
        url: url,
        type: POST,
        data: { userName: userName, userId: userId },
        success: function(data) { },
        error: function(...) { } 
      });
   }
</script>
}

I haven't tested this but it should point you in the right direction.

Upvotes: 1

Robban
Robban

Reputation: 6802

I think the problem here is that the default route is taking precedence.

I'm guessing you have this before your custom route:

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

You need your custom route before this one, otherwise this will be the route that handles requests to your BlogController.

A simple way to solve this would be something like this:

routes.MapRoute(
            name: "userwisedPost",
            url: "Blog/{action}/{userName}",
            defaults: new { controller = "Blog", action = "UserWisedPost", userName = UrlParameter.Optional }
        );

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

This would result in a url like this: Blog/UserWisedPost/SomeUserName?userId=someUserId

Upvotes: 1

Related Questions