Mvc icon indicating copy to clipboard operation
Mvc copied to clipboard

ViewComponent param is null when passed to InvokeAsync()

Open esargent opened this issue 10 years ago • 11 comments

This is my first ViewComponent. Seems straightforward enough after reading Dave Paquette and the example on the aspnet docs site, but the parameter is always getting passed in as null, even though it isn't null from the call in the view.

In the view:

<span>@Component.InvokeAsync("RoleName", roleId).Result</span>  *{roleId = '03bfa663-d484-404c-b9ed-cc16abc7af86' }*

the ViewComponent:

     public class RoleNameViewComponent : ViewComponent

    public RoleNameViewComponent(RoleManager<IdentityRole> roleManager)
    {
        foreach (var r in Enum.GetNames(typeof(MyRoles)))
        {
            roleNameDictionary.Add(
                roleManager.GetRoleIdAsync(
                    new IdentityRole(r)).Result,
                r);
        }
    }

     public async Task<IViewComponentResult> InvokeAsync(string roleId)    *{roleId=null}*
    {
        string name = string.Empty;
        if (roleId == null) { name = "null"; }
        else
        {
            if (!roleNameDictionary.TryGetValue(roleId, out name)) { name = "no match"; }
        }
        return Content(name);

    }

(I see this isn't the best design as the constructor gets called again with every call to the viewcomponent on that page. I'll fix that later. Although I wonder if it is really necessary to have a new instance of the ViewComponent for every call? But that's a separate issue.)

esargent avatar Jan 22 '16 18:01 esargent

Is the roleId provided by the Model or the ViewBag or is it some type of javascript object?

ArieJones avatar Jan 22 '16 20:01 ArieJones

@ArieJones It is calculated with Razor script from the Model.

The Model is @model IEnumerable<Revelar.Models.ApplicationUser>, which is the EF7 ApplicationUser. When debugging I can see that this is getting populated and the roleID is being determined correctly in the View when it makes the call to Component.InvokeAsync.

Here are the details:

 @foreach (var item in Model)
{
    <tr>
       <td>@Html.DisplayFor(modelItem => item.Email)</td>
       <!--Snip some other fields that get displayed-->
        <td>
            @{
                if (item.Roles.Count > 0)
                {
                    string roleId = item.Roles.First().RoleId;
                    <span>@Component.InvokeAsync("RoleName", roleId).Result</span>
                }
                else
                {
                    <span>None</span>
                }
            }
}

and the controller method, which is working,

        public async Task<IActionResult> Index()
    {
        var users = await _context.ApplicationUsers.AsNoTracking().Include(u=>u.Roles).ToListAsync();
        return View(users);
    }

The goal here is just to display a quick admin view of users and their application roles. And also to write a ViewComponent because I wanted to learn how to do that. ;-)

esargent avatar Jan 22 '16 20:01 esargent

It doesn't look like you have done anything wrong here. I tried this out and on a local project and it worked without issue.

I am on RC-1 Update 1 ... so it could just be a version issue that has been addressed ...

ArieJones avatar Jan 22 '16 21:01 ArieJones

I'm using rc2-16770. Can you repo with that?

One of the things I noticed was a big refactor that eliminated the ability to call Invoke(), and now only allows InvokeAsync() that could have impacted this, although it looks like the test coverage should have found something like this so I'm not sure that's it. And I didn't have any ViewComponents before I moved to RC2 so I don't have a baseline.

esargent avatar Jan 22 '16 22:01 esargent

We made some changes here that it looks like we forgot to announce, mostly around streamlining how VCs are invoked, and removing cases that seem like they should work, but don't.

Sorry for the confusion, and expect an official announcement post soon. /cc @pranavkm

We removed @Component.Invoke() - view components almost always do async work, or render another view (which is async). We removed the sync invoke to streamline things and remove forever all questions about 'which one should I use?'

Additional, we removed overloading on parameters for VC methods, and change the style of InvokeAsync to use anonymous objects instead of params object[]. This eliminated a bunch of corner cases around conversions - since there's no overloading on VC methods, we know the exact types of parameters and can do conversions correctly.

So your call site should look like:

  <span>@await Component.InvokeAsync("RoleName", new { roleId = item.Roles.First().RoleId })</span>

rynowak avatar Jan 22 '16 22:01 rynowak

My bad, I forgot to create an announcement thread as part of my change. Here's the announcement and https://github.com/aspnet/Mvc/issues/3973 has discussions for the change.

pranavkm avatar Jan 22 '16 23:01 pranavkm

@rynowak @pranavkm That fixed it. Thank you. And I think the change is good overall - it made sense immediately when I saw it, at least the async part.

It might be helpful to update the documentation from /// Arguments to be passed to the invoked view component method.

Although that comes from the Interface, so maybe the concrete DefaultViewComponentHelper could override the comments to be specific about its expectations? That would have helped a lot. 'object' is a little vague.

BONUS: It would be great if it could operate similar to the way the DisplayAttribute works for view models, although that might be asking too much since you'd have to resolve the class in order to know what the specific ViewComponent is wanting. I'm not sure how far you can take intellisense with that scenario.

(Just saw the announcement post - do you want me to move this suggestion over there?)

esargent avatar Jan 22 '16 23:01 esargent

@esargent Filed https://github.com/aspnet/Mvc/issues/3974 to track the doc improvement.

pranavkm avatar Jan 22 '16 23:01 pranavkm

Since Component.Invoke is removed (is now InvokeAsync) how is it possible to call this component explicitly NOT async? since that is not possible in my current situation.

Daan298261 avatar Sep 17 '17 19:09 Daan298261

@DaanTacoSchool this is a pretty old issue - can you file a new issue describing what you're trying to do? That is, why do you need to call the component synchronously?

Eilon avatar Sep 18 '17 03:09 Eilon

For one, that the method is called from synchronous code directly, but equally important, it is really difficult to unit test this.

Op 18 sep. 2017 05:18 schreef "Eilon Lipton" [email protected]:

@DaanTacoSchool https://github.com/daantacoschool this is a pretty old issue - can you file a new issue describing what you're trying to do? That is, why do you need to call the component synchronously?

— You are receiving this because you were mentioned. Reply to this email directly, view it on GitHub https://github.com/aspnet/Mvc/issues/3970#issuecomment-330121473, or mute the thread https://github.com/notifications/unsubscribe-auth/Ab5Q8W1tJfKHLraFH1CIfxlyai9CUk-Cks5sjeEdgaJpZM4HKlKL .

Daan298261 avatar Sep 18 '17 11:09 Daan298261