簡體   English   中英

如何在另一個視圖中顯示一個視圖

[英]How do I display a View inside another View

我正在通過制作像 Twitter 這樣的網站來練習 ASP 和 MVC,但在使用 PartialView 時遇到了問題。

我在這里有我的用戶主頁控制器,它是從我的登錄頁面控制器調用的。

public class UserController : Controller
{
    private readonly Twitter _twitter = null;
    private readonly TwitterCloneDBContext _context;
    public UserController(TwitterCloneDBContext context)
    {
        _twitter = new Twitter(context);
        _context = context;
    }

    public ActionResult Index()
    {
        List<Tweet> tweets = _twitter.TweetList();
        ViewBag.Tweets = tweets.Count;
        ViewBag.Followers = 2;
        ViewBag.Following = 3;
        return View();
    }

    public PartialViewResult TweetList()
    {
        List<Tweet> tweetList = _twitter.TweetList();
        return PartialView("TweetList",tweetList);
    }
}

這是它的視圖。

 @{
    ViewData["Title"] = "Home Page";
    Layout = "~/Views/Shared/_Layout.cshtml";
}
@using Microsoft.AspNetCore.Http;
@model IEnumerable<Tweet>

@if (Context.Session.GetString("FullName") != null)
{
    <div class="text-center">
        <h1 class="display-4">Welcome, @Context.Session.GetString("FullName")!</h1>
    </div>
    <hr />
    <div class="row">
        <div class="col-sm-2">
            <div class="text-left">
                <h4>Follow</h4>
                <form asp-action="Search">
                    <div class="input-group mb-3">
                        <input type="text" name="searchName" class="form-control" placeholder="Search User" />
                        <div class="input-group-append">
                            <button class="btn btn-primary" type="submit">Search</button>
                        </div>
                    </div>
                </form>
                <span class="text-danger">@ViewBag.SearchFail</span>
            </div>
            <div>
                <h6>@ViewBag.Tweets Tweets</h6>
                <br />
                <h6>@ViewBag.Followers Followers</h6>
                <br />
                <h6>@ViewBag.Following Following</h6>
            </div>
        </div>
        <div class=border></div>
        <div class="col-4">
            <h4>Tweet your thoughts!</h4>
            <form asp-action="Tweet">
                <textarea rows="5" cols="100" name="message" class="form-control"> </textarea>
                <br />
                <input type="submit" value="Tweet" class="btn btn-primary" />
            </form>
            <span class=" text-danger">@ViewBag.ErrMessage</span>
            <div>
               @Html.PartialAsync("TwitterList",Model)            
            </div>
        </div>
    </div>
}
else
{
    <h2>You are not Authorized!</h2>
    <script type="text/javascript">
        window.setTimeout(function () {
            window.location.href = '/Home/UserLogin';
        }, 1000);
    </script>
}

Partial Line 應該調用 TwitterList View,它完美地工作並按預期顯示列表。

@model IEnumerable<TwitterClone.Models.Tweet>

<table class="table">
    <thead>
        <tr>
            <th>
                @Html.DisplayNameFor(model => model.User_ID)
            </th>
            <th>
                @Html.DisplayNameFor(model => model.Message)
            </th>
            <th>
                @Html.DisplayNameFor(model => model.Created)
            </th>
            <th></th>
        </tr>
    </thead>
    <tbody>
@foreach (var item in Model) {
        <tr>
            <td>
                @Html.DisplayFor(modelItem => item.User_ID)
            </td>
            <td>
                @Html.DisplayFor(modelItem => item.Message)
            </td>
            <td>
                @Html.DisplayFor(modelItem => item.Created)
            </td>
        </tr>
}
    </tbody>
</table>

但是當我使用 @Html.PartialAsync() 調用它時,它說失敗了

System.NullReferenceException
  HResult=0x80004003
  Message=Object reference not set to an instance of an object.
  Source=TwitterClone.Views
  StackTrace:
   at AspNetCore.Views_User_TweetList.<ExecuteAsync>d__0.MoveNext() in C:\Users\Cloud\source\repos\TwitterClone\TwitterClone\Views\User\TweetList.cshtml:line 19

並在主頁上給我這個見下面的推文按鈕,這是我的部分視圖

請參閱下面的推文按鈕,這是我的局部視圖,如果我以任何其他方式執行局部視圖,我會在兩個地方都得到 NullReferenceException。 這是我對此的關閉,我無法弄清楚。

編輯:

我的 ViewBags 位於另一個與此處無關的操作中。 他們基本上會打印一條錯誤消息。

NullExceptions 消失了,當我自己打開表視圖時,我的模型不是空的。 但是當通過 Partial 調用時它是空的。 我懷疑這是因為鏈中沒有調用某些東西。

如果我將索引操作更改為這樣,

public ActionResult Index()
        {
            List<Tweet> tweets = _twitter.TweetList();
            ViewBag.Tweets = tweets.Count;
            ViewBag.Followers = 2;
            ViewBag.Following = 3;
            return View("Index",tweets);
        }

我收到這個錯誤。

InvalidOperationException: The model item passed into the ViewDataDictionary is of type 'System.Collections.Generic.List`1[TwitterClone.Models.Tweet]', but this ViewDataDictionary instance requires a model item of type 'TwitterClone.Models.Person'.

我不知道 ViewDataDictionary 在哪里將 Person 設置為。 我能想到的唯一連接到 UserController 的地方是我的 HomeController。
編輯
這是一個愚蠢的錯誤,我在布局文件中遺漏了一個@model Person。 對不起。
編輯

public class HomeController : Controller
    {
        private readonly ILogger<HomeController> _logger;
        private readonly TwitterCloneDBContext _context;

        public HomeController(ILogger<HomeController> logger, TwitterCloneDBContext context)
        {
            _logger = logger;
            _context = context;

        }

        //GET: Home/UserLogin
        public ActionResult UserLogin()
        {
            return View();
        }


        //POST: Home/UserLogin
        [Microsoft.AspNetCore.Mvc.HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult UserLogin(Person userLogin)
        {
            var login = _context.Person.Where(a => a.UserID.Equals(userLogin.UserID)
                                              && a.Password.Equals(userLogin.Password)).FirstOrDefault();
            if (login != null)
            {
                Person session = _context.Person.SingleOrDefault(u => u.UserID == userLogin.UserID);
                session.Active = 1;
                HttpContext.Session.SetString("FullName", login.FullName);
                HttpContext.Session.SetString("UserID", login.UserID);
                _context.SaveChanges();
                return RedirectToAction("Index", "User");
            }
            else
            {
                ViewBag.ErrMsg = "Invalid Credentials";
                return View();
            }           
        }
}

和它的視圖

@model Person
@{
    ViewData["Title"] = "UserLogin";
    Layout = "~/Views/Shared/LoginLayout.cshtml";
}

<h1>Welcome!</h1>

<h4>Enter Credentials</h4>
<hr />
<div class="row">
    <div class="col-md-4">
        <form asp-action="UserLogin">
            <div asp-validation-summary="ModelOnly" class="text-danger"></div>
            <div class="form-group">
                <label asp-for="UserID" class="control-label">User ID</label>
                <input asp-for="UserID" class="form-control" />
                <span asp-validation-for="UserID" class="text-danger"></span>
            </div>
            <div class="form-group">
                <label asp-for="Password" class="control-label">Password</label>
                <input asp-for="Password" class="form-control" />
                <span asp-validation-for="Password" class="text-danger"></span>
            </div>
            <div class="form-group">
                <input type="submit" value="Login" class="btn btn-primary" />
            </div>
        </form>
    </div>   
</div>

<div>
    New User? <a asp-action="Signup">Signup</a>
</div>

什么是

<span class="text-danger">@ViewBag.SearchFail</span>

我在您的操作中看不到 ViewBag.SearchFail 或 ViewBag.ErrMessage。

你有一個大錯誤。 將重定向從索引視圖移動到操作,否則它將在創建頁面后始終運行。

 public ActionResult Index()
    {
      if (Context.Session.GetString("FullName") != null)
        {
 
        List<Tweet> tweets = _twitter.TweetList();
         .....
       
        return View("Index", tweets);
       }
         RedirectToAction("Login", "Users")
    }

由於您對兩者使用相同的模型,請嘗試更換

    @Html.PartialAsync("TwitterList",Model)  

    <partial name="TwitterList" />

並修復兩個視圖的模型

@model List<TwitterClone.Models.Tweet>

還修復了部分視圖

@if(@Model!=null && Model.Count >0)
{
<table class="table">
    <thead>
        <tr>
            <th>
                @Html.DisplayNameFor(model => model[0].User_ID)
            </th>
            <th>
                @Html.DisplayNameFor(model => model[0].Message)
            </th>
          ......
}

暫無
暫無

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

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