Arjun
Arjun

Reputation: 16

How to Use Two Same Model in a View? [MVC4]

I'm trying to create a status update page where I want a user to insert status message in Index page and also, I want to show all inserted all status messages in the same Index page.

This is my Model code:

public class Statuses
{
    [Key]
    public int StatusID { get; set; }
    [DataType(DataType.MultilineText)]
    [Required]
    public string message { get; set; }
}
public class StatusContext : DbContext
{
    public DbSet<Statuses> Status { get; set; }
}

And, I used

@Html.EditorFor(model => model.message)
in the Index.cshtml page.

To show the editor, I used the following model in View.

@model LearnStart.Models.Statuses

However, to show all the status messages below the Multiline TextArea, I think I'm supposed to use the below one.

@model IEnumerable<LearnStart.Models.Statuses>

How to use both model in same view so that I can display both the text area (to insert the status message) and to list all available status messages below it?

Upvotes: 0

Views: 116

Answers (2)

Kartikeya Khosla
Kartikeya Khosla

Reputation: 18873

Easy way is to put a list inside Viewbag and show list in View as shown :-

Controller :

Public Actionresult Myaction()
{
   .........
   Viewbag.data = //bind list of messages here
   return View();
}

View :

@model LearnStart.Models.Statuses
.........
.........
.........
@if(Viewbag.data != null){
 <table>
 @foreach(var item in Viewbag.data)
  {
    <tr><td>@item.message</td></tr>
  }
 </table>
}

Upvotes: -1

Erik Funkenbusch
Erik Funkenbusch

Reputation: 93444

First, you should not be passing your entities directly to your view. The recommended best practice is to use View Models, which are models tailored specifically to your view.

Second, when using a view model you can now do this, since it's not tied to your data model entities:

public class MyActionViewModel {
    public List<StatusesViewModel> StatusList {get;set;}
    public StatusesViewModel CreatedStatus {get;set}
}

Then in your view:

@model MyActionViewModel

@Html.EditorFor(x => x.CreatedStatus)

.............................................

@Html.DisplayFor(x => x.StatusList)

Then you can create two templates, an EditorTemplate and a DisplayTempate:

In ~/Views/Shared/EditorTemplates/StatusesViewModel.cshtml

@model StatusesViewModel

@using(Html.BeginForm()) {
    @Html.EditorFor(x => x.Message)
    <input type="submit" value="Create Status" />
}

In ~/Views/Shared/DisplayTemplates/StatusesViewModel.cshtml

@model StatusesViewModel

<div>
    <span>@Model.Message</span>
</div>

The thing that's nice about using the templates is that they will automatically iterate over your collection.. no foreach or for statement is used. A single EditorFor works on the entire collection, then renders the template based on the type, which in this case translates to StatusViewModel.cshtml

Upvotes: 2

Related Questions