shuan
shuan

Reputation: 136

mvc4 @Html.DropDownListFor use two models or entities?

I am new to MVC.

I have two tables: first one stores the vendor’s information, the other one stores the order details. I want to use the vendor table’s values for the dropdown list.

@model Ore.Domain.Entities.OrderDetail

   @{
      ViewBag.Title = "";
}

<h2> </h2>


@using (Html.BeginForm())
{
       <div>vendor: @Html.DropDownListFor(x=>x.Vendor,’**how to use the value from another entities or models?** ’)</div>
       <div>Contract Number: @Html.EditorFor(x=>x.ContractNo)</div>

Thanks

Upvotes: 0

Views: 548

Answers (2)

Oleksii Aza
Oleksii Aza

Reputation: 5398

Just introduce a model specificly for your view. Let's call it OrderDetailViewModel:

public class OrderDetailViewModel
{
    public Ore.Domain.Entities.OrderDetail Order {get;set;}
    public IEnumerable<SelectListItem> Vendors {get; set;}
}

Then on your view:

@model OrderDetailViewModel

<h2> </h2>


@using (Html.BeginForm())
{
       <div>vendor: @Html.DropDownList("Vendor", Model.Vendors)</div>
       <div>Contract Number: @Html.EditorFor("ContractNo", Model.ContractNo)</div>

Or just pass Vendors throught ViewBag like this: in controller:

ViewBag.Vendors = // populate items as new List<SelectListItem>()

on view:

<div>vendor: @Html.DropDownListFor(n=>n.Vendor, (List<SelectListItem>)ViewBag.Vendors)</div>

Upvotes: 0

Ross Bush
Ross Bush

Reputation: 15185

This is a good example of when you need to break away from your DO and make a hybrid view that either contains composite DO's like a Parent item and a List of Child items or some combination thereof. The more it resembles your DO the more likely that you can leverage mapping techniques such as auto mapper.

Upvotes: 1

Related Questions