development

ASP MVC 3의 한보기에 두 모델

big-blog 2020. 9. 2. 19:50
반응형

ASP MVC 3의 한보기에 두 모델


두 가지 모델이 있습니다.

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

SINGLE 뷰에서 두 클래스의 개체를 편집하려면 다음과 같은 것이 필요합니다.

@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)
}

물론 이것은 작동하지 않습니다. .cshtml 파일에는 하나의 'model'문만 허용됩니다. 몇 가지 해결 방법이 있습니까?


두 모델을 모두 포함하는 상위 뷰 모델을 만듭니다.

public class MainPageModel{
    public Model1 Model1{get; set;}
    public Model2 Model2{get; set;}
}

이렇게하면 최소한의 노력으로 나중에 모델을 추가 할 수 있습니다.


튜플을 사용하려면 다음을 수행해야합니다. 뷰에서 모델을 다음과 같이 변경합니다.

@model Tuple<Person,Order>

@html 메서드를 사용하려면 다음을 수행해야합니다.

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

또는

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

Item1은 Tuple 메서드에 전달 된 첫 번째 매개 변수를 나타내며 Item2를 사용하여 두 번째 모델 등에 액세스 할 수 있습니다.

컨트롤러에서 Tuple 유형의 변수를 만든 다음 뷰에 전달해야합니다.

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

또 다른 예 : 뷰의 여러 모델


커스텀 모델을 생성 할 필요가없는 또 다른 옵션은 Tuple <> 을 사용하는 것 입니다.

@model Tuple<Person,Order>

Andi의 답변에 따라 둘 다 포함하는 새 클래스를 만드는 것만 큼 깨끗하지는 않지만 실행 가능합니다.


매우 평평한 모델을 선호하는 경우보기를 지원하기 위해이 특정보기에 특정한 모델을 만들어야합니다.

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

많은 사람들이 AutoMapper를 사용하여 도메인 개체에서 플랫 뷰로 매핑합니다.

뷰 모델의 아이디어는 단지 뷰를 지원한다는 것입니다. 다른보기에 대해 원하는 속성로드가 아닌 해당보기에 필요한 것만 포함하도록보기 당 하나씩 있습니다.


좋아요, 모두 이해가갑니다. 저는 모든 조각을 가져 와서 설명을 끝낼 필요가있는 저와 같은 초보자를 돕기 위해 여기에 두었습니다.

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. . .


In fact there is a way to use two or more models on one view without wrapping them in a class that contains both.

Using Employee as an example model:

@model Employee

Is actually treated like.

@{ var Model = ViewBag.model as Employee; }

So the View(employee) method is setting your model to the ViewBag and then the ViewEngine is casting it.

This means that,

ViewBag.departments = GetListOfDepartments();
    return View(employee);

Can be used like,

            @model  Employee
        @{
                var DepartmentModel = ViewBag.departments as List<Department>;
        }

Essentially, you can use whatever is in your ViewBag as a "Model" because that's how it works anyway. I'm not saying that this is architecturally ideal, but it is possible.


Just create a single view Model with all the needed information in it, normaly what I do is create a model for every view so I can be specific on every view, either that or make a parent model and inherit it. OR make a model which includes both the views.

Personally I would just add them into one model but thats the way I do it:

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

@model project.Models.Home.xViewModel

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

You can use the presentation pattern http://martinfowler.com/eaaDev/PresentationModel.html

This presentation "View" model can contain both Person and Order, this new
class can be the model your view references.


Another way that is never talked about is Create a view in MSSQL with all the data you want to present. Then use LINQ to SQL or whatever to map it. In your controller return it to the view. Done.


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

Good luck.


Beside of one view model in asp.net you can also make multiple partial views and assign different model view to every view, for example:

   @{
        Layout = null;
    }

    @model Person;

    <input type="text" asp-for="PersonID" />
    <input type="text" asp-for="PersonName" />

then another partial view Model for order model

    @{
        Layout = null;
     }

    @model Order;

    <input type="text" asp-for="OrderID" />
    <input type="text" asp-for="TotalSum" />

then in your main view load both partial view by

<partial name="PersonPartialView" />
<partial name="OrderPartialView" />

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

참고URL : https://stackoverflow.com/questions/5550627/two-models-in-one-view-in-asp-mvc-3

반응형