JustJohn
JustJohn

Reputation: 1460

Call a Task and return True or False MVC 6

I can call this task. I can't seem to understand what is returned. Much less use it. I just want a True or False so I can save a Role or not.

   public ActionResult Create([FromServices]IServiceProvider serviceProvider,string roleName)
    {

        ModelState.Clear();

        try
        {

        var doesit= DoesRoleExist(serviceProvider, roleName);

            if (string.IsNullOrEmpty(roleName))
            {
                throw new Exception("Invalid Role Name: Cannot be empty and must be unique");
            }



             context.Roles.Add(new Microsoft.AspNet.Identity.EntityFramework.IdentityRole()
            {
                Name = roleName,
                NormalizedName = roleName.ToUpper()
            });

            context.SaveChanges();

            return RedirectToAction("Index");
        }
        catch
        {
            ModelState.AddModelError(string.Empty, string.Format("{0}", "Unable to Create Role. "));
            return View();
        }
    } 

I get this when I break on "var doesit=DoesRoleExist(serviceProvider,roleName)"

? doesit

Id = 2093, Status = WaitingForActivation, Method = "{null}", Result = "{Not yet computed}" AsyncState: null CancellationPending: false CreationOptions: None Exception: null Id: 2093 Result: false Status: WaitingForActivation

Here is the Task:

 private async Task<bool> DoesRoleExist(IServiceProvider serviceProvider, string roleName)
        {

            bool result =false;

            var RoleManager = serviceProvider.GetRequiredService<RoleManager<IdentityRole>>();

           result = await RoleManager.RoleExistsAsync(roleName);
           return result;
    }

It's funny but besides the "can't compare boolean using ===" which I ran into when I put an If statement in the ActionResult, I also see that in the above Task, "return result;" runs AFTER "result=await RoleManager.RoleExistsAsync(roleName);". Go figure. Just a simple true or false is all I ask and the ability to compare a boolean to see if I want to add the Role or not.

I want to add that my context.Roles does not have "RoleExists" method. However, for some reason in an async task I can call ".RoleExistsAsync" for some reason.

Upvotes: 1

Views: 724

Answers (1)

JustJohn
JustJohn

Reputation: 1460

As usual with this MVC stuff I just try every random copy and paste I can think of. While looking through This CodeProject item I noticed that you could make an ActionResult async. Thinking this would allow me to avoid calling a task. I went and did this:

    [HttpPost]
   public async Task<ActionResult> Create([FromServices]IServiceProvider serviceProvider,string roleName)
    {

var RoleManager = serviceProvider.GetRequiredService<RoleManager<IdentityRole>>();

try
{

  bool  result = await RoleManager.RoleExistsAsync(roleName);

    //LEFT OUT STRING.EMPTY CHECK FOR BREVITY
   //NOTICE HOW I GOT A BOOLEAN COMPARISON BELOW (OLD AS THE HILLS!)  
        if (result)
        {
            throw new Exception("This Role Name already exists");

        }

//ADD ROLE HERE IF NOT EXISTS AND NOT EMPTY

So I hope my wild ramblings will help someone. Essentially I did not have to deal with the RolesStore way of making a RoleManager and I was able to figure out the async and await stuff enough to use inside of MVC 6 action result.

I am still open to any comments and ways of doing "simple" (LOL) stuff like this. I would gladly fork over an "accepted answer" to someone hungry enough.

Upvotes: 0

Related Questions