簡體   English   中英

如何使用控制器(ASP.NET MVC)的結果填充部分視圖

[英]How can I populate partial view with results from my Controller (ASP.NET M V C)

在開始閱讀之前,請仔細閱讀代碼中的注釋。

我需要顯示當前登錄用戶的未讀電子郵件。

當用戶登錄系統時,將收到有關他有一些未讀電子郵件的通知,並且當用戶單擊電子郵件(該通知)時,應該顯示來自數據庫的真實電子郵件,如下所示:

在此處輸入圖片說明

據我所知,這可能完全是一個javascript初學者,我想我需要附加click事件,該事件將調用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元素,所以代替“ John Doe”我想顯示數據庫中的真實發件人。

任何形式的幫助對我來說都是很好的。

多謝你們

干杯

答案修改為評論。

您需要在主父電子郵件視圖中呈現部分視圖。

主“電子郵件”視圖

@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帖子的返回內容所代替。 然后在帖子的成功部分,替換包含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);
    }

這應該足以使您前進。

如果要使用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>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM