【问题标题】:Display form for creating new message along with message list in ASP.NET MVC 4在 ASP.NET MVC 4 中显示用于创建新消息的表单以及消息列表
【发布时间】:2012-10-26 18:10:41
【问题描述】:

我创建了模型Message 并在我的站点的Index 视图上显示这些消息的列表。控制器将IEnumerable<Models.Message> 对象传递给视图。

为了显示所有这些消息,我使用@foreach 遍历它们。但我也想在同一个Index 视图上创建表单以创建新消息。似乎很容易,但打电话给@Html.TextAreaFor(Model.Body) 会给我以下错误:

CS1061: 'System.Collections.Generic.IEnumerable<Models.Message>' does not contain a definition for 'Body' and no extension method 'Body' accepting a first argument of type 'System.Collections.Generic.IEnumerable<Models.Message>' could be found (are you missing a using directive or an assembly reference?)

是否可以基于Models.Message 创建表单,尽管视图是基于IEnumerable<Models.Message> 创建的?

我的模型是:

public class Message
{
    [BsonId]
    public ObjectId Id { get; set; }

    public Citizen From { get; set; }
    public Citizen To { get; set; }

    [Required]
    [AllowHtml]
    public string Body { get; set; }

    [ScaffoldColumn(false)]
    public DateTime Date { get; set; }

    public bool IsPrivate { get; set; }
}

编辑:坦率地说,我不想创建一个额外的模型来保存一条消息用于表单和用于显示的消息列表,主要是因为在表单操作控制器中我需要处理这个“扩展”模型。我认为更清洁的应该是那里有原始的Message

但是怎么做呢?

【问题讨论】:

  • 你能把你的模型发上来看看吗?

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


【解决方案1】:

是的,这是可能的。您必须为这个特定的视图创建一个(视图)模型,并具有所有必要的属性,如下所示:

public class IndexViewModel(){

    public IEnumerable<Models.Message> Messages {get;set; }

    public string Body {get;set;}

    //any other properties for your form

}

在您的 Controller 中,创建此 ViewModel 并填充它:

public ActionResult Index(){

    var vm = new IndexViewModel();
    vm.Messages = GetMessages();

    return View(vm);
}

在你的视图中,将此ViewModel设置为模型,你可以使用Model.Messages遍历消息,并使用TextAreaFor(x => Model.Body)创建一个textarea

【讨论】:

  • 我得到了方法,简单的答案:我需要额外的模型来处理这种情况。
  • 但是...这意味着在动作控制器中我不能接受原始Message 模型。我需要使用新的。对我来说看起来有点难看,因为新模型包含消息列表的定义。在这种情况下是冗余的......是否可以避免这种情况?
  • 这就是它的缺点。我还没有找到真正的解决方案。您可以将 Message-List 放在 ViewBag 中,因此您不必将它们放在 ViewModel 中。
猜你喜欢
  • 1970-01-01
  • 2012-08-08
  • 1970-01-01
  • 1970-01-01
  • 2012-04-29
  • 2017-04-26
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多