简体   繁体   中英

How to use two models in asp.net mvc on a View?

I have two models and i am struggling to use them on my View for my Form. Any mate who can help me to clarify this better? My logic is as below:

// Two model class here.

    public class RoleViewAndFileViewModel
    {
        public RoleViewModel RoleViewModelData { get; set; }

        public FileViewModel FileViewModelData { get; set; }
    }


//View class
@using eNtsaRegistrationTraining.Models
@RoleViewAndFileViewModel

@{
    ViewBag.Ttile = "Dashboard";
    Layout = "~/Views/Shared/_HomeLayout.cshtml";
}

In a view, you declare your model like @model YourClassName

For exemple, if your model is a list of string, you declare like

@model List<string>

and then, you can use your model in your view like:

@foreach(string s in Model)
{
  <div> @s </div>
}

But, if in your case you need two type of object, you can add a class which contains as parameter your two objects and use it in your view as model like this:

namespace MyMVCapplication
{
 public class MyModelMV
 {
    public MyFirstClas MyFirstClassProp { get; set; }
    public MySecondClass MySecondClassProp { get; set; }
 }

 public class MyFirstClas
 {
    public string Name { get; set; }
    public string Code { get; set; }

 }
 public class MySecondClass
 {
    public double Width { get; set; }
    public double Height { get; set; }
    public string Code { get; set; }
 }
}

And in your view:

  @model MyModelMV

And than you can access to your objects like

<div>@Model.MyFirstClassProp.Name</div>
<div>@Model.MySecondClassProp.Code</div> 
...
...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM