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

bigbear
 
on Apr 08, 2019 12:06 AM
3139 Views

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>
            <div class="panel-body">
                @using(Html.BeginForm("GetUserRole", "Admin"))
                {
                    @Html.AntiForgeryToken()
                    <p>
                        User Name: @Html.DropDownList("username",
                                   (IEnumerable<SelectListItem>)
                                   ViewBag.Users, "Select ...")
                        <input type="submit" value="Get User Role" 
                               class="btn btn-info" />
                    </p>
                }
                @if(ViewBag.RolesForUser != null)
                {
                    <div class="alert alert-info">
                        <strong>Role for User</strong>
                        <ol>
                            @foreach(string str in ViewBag.RolesForUser)
                            {
                                <li>@str</li>
                            }
                        </ol>
                    </div>
                }
            </div>
        </div> 

 

[ValidateAntiForgeryToken]
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
dharmendr
 
on Apr 08, 2019 12:12 AM