Pass Data from Controller to View without Model or ViewBag in ASP.Net MVC

on Apr 08, 2019 12:06 AM

I have a quick question just wondering whats the best way to do this. I normally use viewbag but is there a different way I should be doing this because I heard viewbag isn't a good thing to do often.

I get a user by their username and then I get the list of their roles with an [httppost].

How should I pass the roles back to the view? I already have a model of a user inserted into the view @model

so I cant insert it like that return view(). What should I be doing for this?

        <div class="panel panel-primary">
            <div class="panel-heading text-center">
                <h4>Get Role for Selected User</h4>
            <div class="panel-body">
                @using(Html.BeginForm("GetUserRole", "Admin"))
                        User Name: @Html.DropDownList("username",
                                   ViewBag.Users, "Select ...")
                        <input type="submit" value="Get User Role" 
                               class="btn btn-info" />
                @if(ViewBag.RolesForUser != null)
                    <div class="alert alert-info">
                        <strong>Role for User</strong>
                            @foreach(string str in ViewBag.RolesForUser)


public async Task<ActionResult> GetUserRole(string username)
    if (!string.IsNullOrWhiteSpace(username))
        var user = await UserManager.FindByNameAsync(username);
        var roles = await UserManager.GetRolesAsync(user.Id);
        // ?? ?? or a different way
        ViewBag.RolesForUser = roles;
    return RedirectToAction("RoleManager", "Admin");


Download FREE API for Word, Excel and PDF in ASP.Net: Download
on Apr 08, 2019 12:12 AM