shytikov
shytikov

Reputation: 9558

Display form for creating new message along with message list in ASP.NET MVC 4

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?

Upvotes: 0

Views: 779

Answers (1)

Pbirkoff
Pbirkoff

Reputation: 4702

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)

Upvotes: 1

Related Questions