1

I have a View Component in _Layout.cshtml. My application has a route of /home/{id}. How can I get the id value in my URL route from the View Component controller?

public class LayoutViewComponent : ViewComponent
{
    public async Task<IViewComponentResult> InvokeAsync()
    {
        //how do I get the value of {id} here?

        return View();
    }
}

1 Answer 1

2

You do not want view to go and get the required parameter from query string by itself. It could strict the usage of the view.

Instead, you could pass Id from parent.

// Parent's Action Method
public IActionResult ParentActionMethod(int id)
{
    // You could use strongly typed model
    ViewBag.Id = 1;
    return View(); 
}    

// Parent's View
@await Component.InvokeAsync("Layout", new { Id = ViewBag.Id })

// View Component
public class LayoutViewComponent : ViewComponent
{
    public async Task<IViewComponentResult> InvokeAsync(int id = 10)
    {
        return View();
    }
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.