0

I've created model Message and showing list of these messages on Index view of my site. The controller passes IEnumerable<Models.Message> object to the view.

To display all these messages I'm iterating through them using @foreach. But I also want to create form on the same Index view to create new message. Seems to be easy task, but call to @Html.TextAreaFor(Model.Body) gives me following error:

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?)

Is it possible to create form based on Models.Message, despite fact that view as created based upon IEnumerable<Models.Message>?

My model is:

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; }
}

EDIT: Frankly I don't want to create an additional model holding one message for form and list of messages for display, mostly since in form action controller I need to deal with this "extended" model. I think cleaner would be to have original Message there.

But how?

shytikov
  • 9,155
  • 8
  • 56
  • 103

1 Answers1

1

Yes, that's possible. You will have to create a (View)Model for this particular view, with all the necessary properties like this:

public class IndexViewModel(){

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

    public string Body {get;set;}

    //any other properties for your form

}

In your Controller, create this ViewModel and populate it:

public ActionResult Index(){

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

    return View(vm);
}

In your view, set this ViewModel as the model, and you can iterate through the messages by using Model.Messages, and create a textarea using TextAreaFor(x => Model.Body)

Pbirkoff
  • 4,642
  • 2
  • 20
  • 18
  • I got the approach, the simple answer: I need additional model to handle this situation. – shytikov Oct 26 '12 at 09:49
  • However... This means that in action controller I cannot accept original `Message` model. I need to use new one. What looks a bit ugly to me, since that new model contains definition of messages list. Redundant in this case... Is it possible to avoid this? – shytikov Oct 26 '12 at 10:08
  • That's the downside of this. I haven't found a real solution to this. You could put the Message-List in a ViewBag, so you don't have to put them in the ViewModel. – Pbirkoff Oct 26 '12 at 10:23
  • Currently I'm investigating following link: http://stackoverflow.com/questions/4764011/multiple-models-in-a-view – shytikov Oct 26 '12 at 10:24