Two models in one view in ASP MVC 3

2018-12-31 16:27发布

I have 2 models:

public class Person
{
    public int PersonID { get; set; }
    public string PersonName { get; set; }
}
public class Order
{
    public int OrderID { get; set; }
    public int TotalSum { get; set; }
}

I want edit objects of BOTH classes in SINGLE view, so I need something like:

@model _try2models.Models.Person
@model _try2models.Models.Order

@using(Html.BeginForm())
{
    @Html.EditorFor(x => x.PersonID)
    @Html.EditorFor(x => x.PersonName)
    @Html.EditorFor(x=>x.OrderID)
    @Html.EditorFor(x => x.TotalSum)
}

This, of course, don't work: Only one 'model' statement is allowed in a .cshtml file. May be there is some workaround?

11条回答
后来的你喜欢了谁
2楼-- · 2018-12-31 17:11

If you are a fan of having very flat models, just to support the view, you should create a model specific to this particular view...

public class EditViewModel
    public int PersonID { get; set; }
    public string PersonName { get; set; }
    public int OrderID { get; set; }
    public int TotalSum { get; set; }
}

Many people use AutoMapper to map from their domain objects to their flat views.

The idea of the view model is that it just supports the view - nothing else. You have one per view to ensure that it only contains what is required for that view - not loads of properties that you want for other views.

查看更多
后来的你喜欢了谁
3楼-- · 2018-12-31 17:12

you can't declare two model on one view, try to use Html.Action("Person", "[YourController]") & Html.Action("Order", "[YourController]").

Good luck.

查看更多
旧人旧事旧时光
4楼-- · 2018-12-31 17:15

I hope you find it helpfull !!

i use ViewBag For Project and Model for task so in this way i am using two model in single view and in controller i defined viewbag's value or data

List<tblproject> Plist = new List<tblproject>();
            Plist = ps.getmanagerproject(c, id);

            ViewBag.projectList = Plist.Select(x => new SelectListItem
            {
                Value = x.ProjectId.ToString(),
                Text = x.Title
            });

and in view tbltask and projectlist are my two diff models

@{

IEnumerable<SelectListItem> plist = ViewBag.projectList;

} @model List

查看更多
浅入江南
5楼-- · 2018-12-31 17:16

ok, everyone is making sense and I took all the pieces and put them here to help newbies like myself that need beginning to end explanation.

You make your big class that holds 2 classes, as per @Andrew's answer.

public class teamBoards{
    public Boards Boards{get; set;}
    public Team Team{get; set;}
}

Then in your controller you fill the 2 models. Sometimes you only need to fill one. Then in the return, you reference the big model and it will take the 2 inside with it to the View.

            TeamBoards teamBoards = new TeamBoards();


        teamBoards.Boards = (from b in db.Boards
                               where b.TeamId == id
                               select b).ToList();
        teamBoards.Team = (from t in db.Teams
                              where t.TeamId == id
                          select t).FirstOrDefault();

 return View(teamBoards);

At the top of the View

@model yourNamespace.Models.teamBoards

Then load your inputs or displays referencing the big Models contents:

 @Html.EditorFor(m => Model.Board.yourField)
 @Html.ValidationMessageFor(m => Model.Board.yourField, "", new { @class = "text-danger-yellow" })

 @Html.EditorFor(m => Model.Team.yourField)
 @Html.ValidationMessageFor(m => Model.Team.yourField, "", new { @class = "text-danger-yellow" })

And. . . .back at the ranch, when the Post comes in, reference the Big Class:

 public ActionResult ContactNewspaper(teamBoards teamboards)

and make use of what the model(s) returned:

string yourVariable = teamboards.Team.yourField;

Probably have some DataAnnotation Validation stuff in the class and probably put if(ModelState.IsValid) at the top of the save/edit block. . .

查看更多
余欢
6楼-- · 2018-12-31 17:23

To use the tuple you need to do the following, in the view change the model to:

@model Tuple<Person,Order>

to use @html methods you need to do the following i.e:

@Html.DisplayNameFor(tuple => tuple.Item1.PersonId)

or

@Html.ActionLink("Edit", "Edit", new { id=Model.Item1.Id }) |

Item1 indicates the first parameter passed to the Tupel method and you can use Item2 to access the second model and so on.

in your controller you need to create a variable of type Tuple and then pass it to the view:

    public ActionResult Details(int id = 0)
    {
        Person person = db.Persons.Find(id);
        if (person == null)
        {
            return HttpNotFound();
        }
        var tuple = new Tuple<Person, Order>(person,new Order());

        return View(tuple);
    }

Another example : Multiple models in a view

查看更多
登录 后发表回答