MVC 3 Display data from different Models in the on

2019-06-24 04:04发布

问题:

In the MVC 3 View I want to display a single Contract and a list of Claims, the user will be able to create a new claim. I have created a different view for Contract and Claims how can I merge these so that there is only one view.


Darin,

How do I pass an instance of MyViewModel as the view is looking for two strings?

public ActionResult Details(int id)
{
   MyViewModel myView = new MyViewModel ();
   return View(_repository.GetContract(id), myView); 
}

Thanks


I was using PartialViews Html but I don't see how to pass the model as a parameter.

Contract View @model Portal.Models.Contracts @using Portal.Models

Display data.

<div>
    @{
      Html.RenderPartial("_Claim", Portal.Models.Contracts); 

    }
</div>

I am getting an error CS0119: 'Models.Contracts' is a 'type', which is not valid in the given context.

The data is bound to the Contract View here

public ActionResult Details(int id)
{
    return View(_repository.GetContract(id);
}

How is the data bound to the PartialView _Claim which is of type IEnumerable<Models.Claims> ?

回答1:

You could define a view model which will wrap those two models:

public class MyViewModel
{
    public Contract Contract { get; set; }
    public Claim[] Claims { get; set; }
}

then have your controller action pass an instance of MyViewModel to the view and inside this view use display templates:

@model MyViewModel

@Html.DisplayFor(x => x.Contract)
@Html.DisplayFor(x => x.Claims)

and then define display templates for the Contract and Claim models (~/Views/Shared/DisplayTemplates/Contract.cshtml and ~/Views/Shared/DisplayTemplates/Claim.cshtml).