将数据从ViewModel传递到View和PartialView时出现问题

时间:2017-06-22 17:39:04

标签: c# asp.net asp.net-mvc asp.net-mvc-4 razor

我正在构建一个非常简单的博客。对于我的博客,我需要两个模型:评论和消息。我知道在你的视图中使用两个模型你需要一个ViewModel,但我有一些困难。出于某种原因,我无法访问这两个模型,同样是我的局部视图。现在我对asp.net mvc很新,并且知道这可能是一个愚蠢的错误,但我希望有人可以告诉我我做错了什么,最重要的原因!

以下是我的模特

namespace Portfolio.Models
{
    public class Messages
    {
        public int MessagesId { get; set; }
        [Required]
        public string Title { get; set; }
        [Required]
        public string Body { get; set; }
        public DateTime WhenCreated { get; set; }

        public Messages()
        {
            WhenCreated = DateTime.Now;
        }
    }
}

namespace Portfolio.Models
{
    public class Comments
    {
        public int CommentsId { get; set; }
        public string Comments_body { get; set; }
        public Messages MessagesId { get; set; }
        public DateTime WhenCreated { get; set; }

        public Comments()
        {
            WhenCreated = DateTime.Now;
        }
    }
}

这是我的ViewModel

namespace Portfolio.ViewModels
{
    public class MessageViewModel
    {
        public IEnumerable<Messages> Messages { get; set; }
        public IEnumerable<Comments> Comments { get; set; }
    }
}

我的控制器

    namespace Portfolio.Controllers
{
    public class MessagesController : Controller
    {
        private ApplicationDbContext _context;

        public MessagesController()
        {
            _context = new ApplicationDbContext();
        }

        protected override void Dispose(bool disposing)
        {
            _context.Dispose();
        }
        public ActionResult Blog()
        {
            var messages = _context.messages.ToList();

            return View(_context.messages.OrderByDescending(Messages => 
            Messages.WhenCreated));
        }

        public ActionResult Comment()
        {
            var comment = _context.comments.ToList();

            return View(_context.comments.OrderByDescending(Comments => 
            Comments.WhenCreated));
        }
        public ActionResult Post()
        {
            return View();
        }


        //This binds the objects from the database to the values from the 
        view

        [ValidateInput(false)]
        [HttpPost]
        public ActionResult Create(FormCollection formValues)
        {
            try
            {
                Messages message = new Messages();
                message.Title = formValues["Title"];
                message.Body = formValues["editor"];

                Comments comment = new Comments();
                comment.Comments_body = formValues["editor" + 
                message.MessagesId];

                _context.comments.Add(comment);
                _context.SaveChanges();
                _context.messages.Add(message);
                _context.SaveChanges();

           }
            catch
            {
                return View();
            }
            return RedirectToAction("Blog");
       }
    }
}

这是我的观点

@model IEnumerable<Portfolio.ViewModels.MessageViewModel>

@{
    ViewBag.Title = "Blog";
    Layout = "~/Views/Shared/_Layout.cshtml";
 }
<link rel="stylesheet" type="text/css" href="~/Content/css/Blog.css" />
<script src="~/Scripts/ckeditor/ckeditor.js"></script>

<div class="jumbotron opacity_container">
    <div class="row">
        <div class="col-md-12">
            <h2>Latest Posts</h2>
            <div class="row">
                <div class="col-md-12">
                    @foreach (var messages in Model)
                    {
                        <div class="jumbotron opacity_container">
                            <div class="col-md-12">
                                <div class="panel panel-primary">
                                    <div class="panel-heading">
                                        @*Gets the title of the blog post*@
                                        <h2 class="panel-title">
                                        @messages.Title
                                        </h2>@messages.WhenCreated
                                   </div>
@*Gets the body of the blog post and decodes the html of the ckeditor*@

                                <div class="panel-body">
                 @Html.Raw(System.Web.HttpUtility.HtmlDecode(messages.Body))
                                </div>
                            </div>
                        </div>
 @*this button gets the id from the database of the 
 Message table this helps to prevent that all the comments from all blogs 
 gets shown and thus shows only the comments that belong to the blog in 
 question*@

                    <button class="btn btn primary"id="@messages.MessagesId"
                    onclick="ShowComments(this.id)">
                    Show Comments
                    </button>

@*this is the container where al the comments are placed in and where you 
can post comments. The comments are placed in the Comment partial view*@
                        <div class="hidden" id="Comm@(messages.MessagesId)">
                            @Html.Partial("_Comment", Model)

@*this button gets the id from the database of the Message table this helps 
to prevent that all the comments from all blogs gets hidden and thus
hides only the comments that belong to the blog in question*@
                        <button class="btn btn-primary" 
                        id="@messages.MessagesId" 
                        onclick="HideComments(this.id)">Hide Comments
                        </button>
                    </div>
                </div>
                }
            </div>
        </div>
    </div>
</div>

这是我的部分观点

@{
   ViewBag.Title = "Home Page";
}
<link rel="stylesheet" type="text/css" href="~/Content/css/Blog.css" />

<div class="row" id="CommentContainer">
    <div class="col-md-12">
        <h3>Post Comment</h3>
 @*The form to post comments*@
        @using (Html.BeginForm("Create", "Messages"))
            {
            <div class="form-group">
                <label>Comment</label>
                @Html.TextArea("editor1", htmlAttributes: new { name = 
               "editor1", id = "editor", rows = "10", cols = "180" })
            </div>
                <button type="submit" class="btn btn-primary" 
              id="PostButton">Post Comment</button>
            }

 @*CKEdito script*@
        <script>
             CKEDITOR.replace('editor1');
        </script>


        <div class="row">
            <div class="col-md-10">
@*Places al the comments and decodes the html from the ckeditor*@
                @foreach(var comments in Model)
                {
                    <div class="well" id="CommentBox">

@Html.Raw(System.Web.HttpUtility.HtmlDecode(comments.Comments_body))
                    </div>
                }
            </div>
        </div>
    </div>
</div>

此PartialView在View显示博客消息时显示评论。 所以我需要将我的消息模型中的数据发送到我的View,我需要在部分视图中从我的评论模型中发送和检索数据。

感谢帮助!

1 个答案:

答案 0 :(得分:0)

要在View中使用ViewModel,您需要将其从控制器传递到视图。您目前正在传递一系列消息:

 public ActionResult Blog()
    {
        var messages = _context.messages.ToList();

        // Your view is expecting a parameter of type MessageViewModel,
        // but you're passing it an object of type List<Messages>
        return View(_context.messages.OrderByDescending(Messages => 
        Messages.WhenCreated));
    }

如果您想使用ViewModel,请尝试以下方法:

     public ActionResult Blog()
    {
        //Create a MessageViewModel and assign its properties...
        var viewModel = new MessageViewModel()
        {
           Messages = _context.messages.OrderByDescending(m => m.WhenCreated),
           Comments =  _context.comments
        };

        // Pass the MessageViewModel to your view.
        return View(viewModel);
    }

您还需要更新您的观点:

@model Portfolio.ViewModels.MessageViewModel
...
@foreach (var messages in Model.Messages)
...
@Html.Partial("_Comment", Model.Comments)

并且您希望部分视图采用参数 IEnumberable<Comments>因为它是模型:

@model IEnumerable<Portfolio.Models.Comments>

请注意,此解决方案目前正在从_context获取所有消息和所有条评论并将其传递给视图。您可能希望过滤它们(仅传递附加到特定消息的注释等)。

相关问题