如何使用我的Controller(ASP.NET M V C)的结果填充局部视图

时间:2017-05-31 10:19:06

标签: javascript jquery ajax asp.net-mvc

在您开始阅读之前,请仔细阅读代码中的注释。

我需要为当前登录的用户显示未读电子邮件。

当用户登录系统时,会有通知他有一些未读的电子邮件,当用户点击电子邮件时(该通知),应该显示来自数据库的真实电子邮件,如下所示:

enter image description here

据我所知,这可能作为一个javascript absolutly初学者,我想我需要附加点击事件,它将调用javascript方法,它将对我的控制器进行ajax调用,这将返回一些结果(来自数据库的未读消息)对我来说。

现在我将发布您在上面看到的图像代码:

<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 that you saw on image above

     int unredEmails = EmailController.GetNumberOfUnreadEmails(LoggedInUser.Id);
     if (unredEmails > 0)
     {
        <span class="badge bg-orange" id="inboxunredEmails">@unredEmails</span>
     }

    }
 </a>

 // HERE I AM SHOWING UNREAD MESSAGES AS DROPDOWN (that HTML that is disaplyed when it's clicked on letter) AND I AM PLANING TO MOVE THIS CODE TO A PARTIAL VIEW SO THIS PART MIGHT LOOK LIKE THIS :  `@Html.Partial("_TopNavEmails");`

  <ul id="menu1" class="dropdown-menu list-unstyled msg_list" role="menu">

    int unredEmails = EmailController.GetNumberOfUnreadEmails(LoggedInUser.Id);
    if (unredEmails > 0)
    {
       for (int i = 0; i < unredEmails; i++)
       {
         <li>
            <a>
              <span class="image"><img src="/myresources/images/john.png"></span>
                <span>
                    <span>John Doe</span>
                     <span class="time">3 mins ago</span>
                    </span>
                    <span class="message">
                      Message number: @i;
                    </span>
            </a>
         </li>
        }
     }
  </ul>

正如你可以看到人们在信件上点击我附加点击事件:

onclick="GetAllUnreadEmails('@LogedUserId') 

以下是GetAllUnreadEmails javascript方法的定义:

<script>
    var GetAllUnreadEmails = function (userId) {
        if (userId) {
            $.ajax({
                method: "GET",
                url: '@Url.Action("GetAllUnreadEmails", "Email"),
                contentType: "application/json; charset=utf-8",
                success: function (data) {
                  PROBALY HERE I SHOULD SEND DATA TO PARTIAL VIEW
                },
                error: function (response, textStatus, errorThrown) {
                    alert("error!");
                },
                failure: function (response) {
                    alert("failure!");
                }
            });
        }
    }
</script>

这里是GetAllUnreadEmails ActionMethod,它应该从我的控制器将数据检索回PartialView:

public ActionResult GetAllUnreadEmails()
{  

    //This is global user that I can access to on view also
    if (User.Id != null)
    {
        List<Emails> resultList = EmailController.GetUnreadEmailsByUserId(User.Id);
        return PartialView(resultList);
     }
     return PartialView("Error, not found!");
}

我想我到目前为止所做的这一部分有一定意义,但我被困在这里我不知道如何成功将数据发送到局部视图并使用该数据来填充我的span元素,所以相反&#34; John Doe&#34;我想从数据库中显示真实的发件人。

任何形式的帮助对我来说都很棒。

谢谢你们

干杯

2 个答案:

答案 0 :(得分:1)

回答修改为评论..

您需要在主要的父电子邮件视图中呈现部分视图..类似于......

主要&#34;电子邮件&#34;图

@model TestMVC.Controllers.EmailModel

@{
    Layout = null;
}

<!DOCTYPE html>

<html>
<head>
    <meta name="viewport" content="width=device-width" />
    <title>Emails</title>
</head>
<body>
    <div>
        <i class="fa fa-envelope-o"></i>

        @if (Model.NoOfUnReadEmails > 0)
        {
            <span class="badge bg-orange" id="inboxunredEmails">@Model.NoOfUnReadEmails</span>
        }


        <div id="divUnReadEmails">
            @Html.Partial("_UnReadEmails")
        </div>
</div>
</body>
</html>

这个局部视图被ajax帖子的返回内容所取代。 然后在帖子的Success部分中,替换包含div的html内容。

 success: function(data) {
          $("#divUnReadEmails").html(data);
 }

查看您的代码...我认为您的部分视图将包含以下内容。

@model TestMVC.Controllers.EmailModel

<ul id="menu1" class="dropdown-menu list-unstyled msg_list" role="menu">

    @for (int i = 0; i < Model.Emails.Count; i++)
    {
        <li>
            <a>
                <span class="image"><img src="/myresources/images/john.png"></span>
                <span>
                    <span>@Model.Emails[i].EmailFor</span>
                    <span class="time">@Model.Emails[i].NoOfMinsAgoSent mins ago</span>
                </span>
                <span class="message">
                    Message number: @i;
                </span>
            </a>
        </li>
    }
</ul>

在您的控制器中,使用您需要的初始数据返回主电子邮件视图。

 public ActionResult Emails()
    {
        var emailModel = new EmailModel();
        var emailService = new EmailService();

        emailModel.NoOfUnReadEmails = emailService.GetNoOfUnreadEmails("User1") //Your count!
        emailModel.Username = "User!"; //Logged on user

        return View("Emails", emailModel);
    }

然后您可以返回给定用户的部分视图。

    public PartialViewResult UnReadEmails(EmailModel model)
    {
        var newEmailModel = new EmailModel();
        var emailService = new EmailService();
        newEmailModel.Emails = emailService.GetUnReadEmails(model.Username);

        return PartialView("_UnReadEmails", newEmailModel);
    }

这应该足以让你去..

答案 1 :(得分:0)

如果你想用ajax最好的方法来做到这一点: 首先,您需要将GetAllUnreadEmails方法从控制器更改为:

public JsonResult GetAllUnreadEmails()
{  

    //This is global user that I can access to on view also
    if (User.Id != null)
    {
        List<Emails> resultList = EmailController.GetUnreadEmailsByUserId(User.Id);
        return Json(resultList);
     }
     return Json(false);
}

和ajax调用:

//if the user id is global then there is no need to send it via ajax
    <script>
        var GetAllUnreadEmails = function () {
                $.ajax({
                    method: "GET",
                    url: '@Url.Action("GetAllUnreadEmails", "Email")',
                    contentType: "application/json; charset=utf-8",
                    success: function (data) {
                       $('#menu1').html(' ') //to clear the contect
                       $.each(data, function () {
                           $('#menu1').append("<p>"+this.Name + " " + this.Email+"<p>")
                      })
                    },
                    error: function (result) {
                        alert("error!");
                    },
                    failure: function (response) {
                        alert("failure!");
                    }
                });

        }
    </script>