Olmy
Olmy

Reputation: 95

Retreiving unadorned Action name from within the Action

I have an action method:

[Area("Waffles")]
public class WafflesController : Controller
{
    [HttpGet("/waffles/edit/{id?}", Name = nameof(EditView))]
    public IActionResult EditView( int id ) {
        ...
        return View();
    }
}

In other views/actions I can retrieve the URL (/waffles/edit) of this with either:

url = urlHelper.Action(nameof(WafflesController.EditView));

url = urlHelper.RouteUrl(nameof(WafflesController.EditView));
        

Inside the view/action itself however both calls return the URL & path parameter, i.e. at http://me.com/waffles/edit/1234 both UrlHelper methods return "/waffles/edit/1234", is there a way for me to return just "/waffles/edit" as I can from elsewhere?

Edit

To clarify, inside the view launched from the action above urlHelper.RouteUrl(nameof(WafflesController.EditView)); returns the route URL + its id: "/waffles/edit/1234" I want just /waffles/edit/ in a string.

Upvotes: 1

Views: 58

Answers (1)

LouraQ
LouraQ

Reputation: 6881

is there a way for me to return just "/waffles/edit"

To hide the id in url, you can use ajax get and TempData to achieve:

View:

<a href="waffles/edit" id="1234">Edit</a>
 
@section Scripts{
    <script>
        $("a").click(function () {
            event.preventDefault();
            var id = $(this).attr("id");
            var url = $(this).attr("href");
            $.ajax({
                url: url,
                type: "get",
                data: { "id":  id },
                success: function () {
                    window.location.href = url;
                },
            })

        })

    </script>

}

Action:

[HttpGet("/waffles/edit", Name = nameof(EditView))]
public IActionResult EditView(int? id)
{
    if (id == null && TempData["Data"] != null)
    {
        id = Convert.ToInt32(TempData["Data"]);
    }
    else
    {
        TempData["Data"] = id;
    }

    return View();
}

Update

I need /waffles/edit in a string within the view (without its id)

Just try this code:

 string url = "/waffles/edit/1234";
 url = url.Remove(url.Length - (url.Split('/')[3].ToString().Length + 1));

Upvotes: 1

Related Questions