2

I need to display unread emails for currenty logged in user.

When user logs in to a system there will be notification that he has some unread emails and it looks like this:

LETTER WITH NUMBER OF UNREAD EMAILS ON TOP OF IT

This image indicated that there are 2 messages left to be read.

I want to achieve here when user clicks on this letter to display unread emails/messages.

As much as I understand how this might work as a javascript absolutly beginner I guess I need to attach on click event which will call javascript method which will make an ajax call to my controller which will return some results (unread messages from database) to me.

But I really don't know how is this going in fact... Because I'm really bad with javascript...

Now I will post my code here (and explain it more detailed):

<li role="presentation" class="dropdown">
  <a href="javascript:;" onclick="GetAllUnreadEmails('@LogedUserId') class="dropdown-toggle info-number" data-toggle="dropdown" aria-expanded="false" style="visibility:@visibility;">
         <i class="fa fa-envelope-o"></i>
             @if (LoggedInUser != null)
             {
                            // HERE I AM SHOWING ICON LETTER AND NUMBER OF UNREAD emails ON TOP OF
                            int unredEmails = EmailController.GetNumberOfUnreadEmails(LoggedInUser.Id);
                            if (unredEmails > 0)
                            {
                                <span class="badge bg-red" id="inboxunredEmails">@unredEmails</span>
                            }
                            else
                            {
                                <span class="badge bg-green">@unredEmails</span>
                            }

                        }
      </a>

                    // HERE I AM SHOWING UNREAD MESSAGES AS DROPDOWN 
                    <ul id="menu1" class="dropdown-menu list-unstyled msg_list" role="menu">
                        @if (LoggedInUser != null)
                        {
                            int unredEmails = EmailController.GetNumberOfUnreadEmails(LoggedInUser.Id);
                            if (unredEmails > 0)
                            {
                                for (int i = 0; i < unredEmails; i++)
                                {
                                    <li>
                                        <a>
                                            <span class="email">
                                                Unread Email number: @i;
                                            </span>
                                        </a>
                                    </li>
                                }
                            }
                         }
                    </ul>
</li>

As you can see guys on letter click I attached on click event:

onclick="GetAllUnreadEmails('@LogedUserId') 

Here is definition of GetAllUnreadEmails javascript method:

var GetAllUnreadEmails = function (loggedUserId) {
        if (loggedUserId) {
            $.ajax({
                url: "Message/GetUnreadEmails",
                method: "GET",
                data: {UserID : loggedUserId},
                contentType: "application/json; charset=utf-8",
                success: function (data) {

                },
                error: function (response, textStatus, errorThrown) {
                    alert("error: Error!");
                },
                failure: function (response) {
                    alert("failure: Error!");
                }
            });
        }
    }

And here is my controller and most confusing part for me, because I don't know how and what to return here and how to work with that results that I've returned. Basically I should get list here and foreach item I should generate my html which is creating / displaying unread emails when it's clicked on letter.

public ActionResult GetUnreadEmails(Guid emailId)
  {
     if (User.Id != null)
     {
        List<Emails> resultList = EmailController.GetUnreadEmailsByUserId(User.Id);
        return View(resultList);
     }
     return View("Error, not found!");
  }

I should return Json here? But I event dont how to work with that? I am really confused on this part, or maybe I should loop throght results in this javascript method using .each method of jQuERY ?

Whatever I don't know how to repeat this code

for (int i = 0; i < unredEmails; i++)
{
     <li>
       <a>
           <span class="email">
                  Unread Email number: @i;
           </span>
       </a>
    </li>
}

Really I dont know what to do at this part, because I need to get unread messages everytime user clicks on letter and I can't leave it loaded once because emails can be read in another browser (so value on letter wont be 2 anymor, it will be changed to 1) so when I CLICK on letter without rendering page I must go to database and get "updated data" etc etc..

Whatever any kind of help would be great! Thanks guys Cheers

Roxy'Pro
  • 4,216
  • 9
  • 40
  • 102

1 Answers1

1

You have a variety of options. I prefer returning JSON from my controller methods because it is flexible, but since you aren't comfortable with JavaScript, let's return a view from the controller method instead.

In other words, we'll render the inbox on the server using c#/Razor rather than rendering the inbox in the browser using JavaScript.

  1. Call your controller method with JavaScript (this is your GetAllUnreadEmails() method).
  2. Build a model containing the list of emails.
  3. Populate a view with just the markup needed to render the unread emails.
  4. Return the view using PartialView() instead of View()
  5. You now have a nice fragment of HTML which can be used to update the page.

Your success callback can insert this HTML as desired.

success: function (data) {
    console.log(data);

    $("#id-of-unread-messages-element").html(data);
}

Dealing with Changing Inbox Counts

You also mention changing "unread" values as messages are read (possibly in different locations). Keeping that value in sync is beyond the scope of this answer, but you may want to investigate SignalR for pushing updates to all connected browsers as the changes happen.

SignalR

Tim M.
  • 53,671
  • 14
  • 120
  • 163
  • this is right approach and I almost get it, but still I am struggling with populating my data on partial view, if you want I could leave you a link of another questions but whatever thanks a lot – Roxy'Pro May 31 '17 at 09:32
  • You can link me to another question if you want. – Tim M. May 31 '17 at 13:44
  • here it is mate https://stackoverflow.com/questions/44288057/child-actions-are-not-allowed-to-perform-redirect-actions-using-partialviews/44294620#44294620 – Roxy'Pro May 31 '17 at 22:56