2017-03-28 44 views
0

1模型:如何在MVC中使用強類型視圖綁定一個模型以創建下拉列表和第二個文本框模型?

public class VehicleMake 
{ 
    [Key] 
    public int MakeId { get; set; } 
    public string Make { get; set; } 
} 

第二型號:

public class VehicleModel 
{ 
    [Key] 
    public int ModelId { get; set; } 
    public string Model { get; set; } 
    public DateTime Year { get; set; } 
    public int MakeId { get; set; } 
    public VehicleMake VehcileMake { get; set; } 
} 

如何通過兩個型號爲強類型的視圖。

我的觀點具有 2)一個文本框結合製作和makeid從VehicleMake類作爲模型1)一個下拉列表,從vehicleModle類結合

請建議如何創建使用多個模型視圖?

@model MvcApplication1.Data.ViewVMModel 
.... 
<h2>CreateModel</h2> 
<table> 
    <tr> 
     <td>@Html.Label("Select Make")</td> 
     <td>@Html.DropDownListFor(model=>model.VehicleMake,new SelectList(Model. "MakeId","Make")))</td> 
    </tr> 
    <tr> 
     <td>Enter Model </td> 
     <td>@Html.TextBoxFor(model=>model.VehcileModel)</td> 
    </tr> 
</table> 
+1

'VehcileModel'是一個複雜的對象,你不能一個文本框綁定到一個複雜的目的。你是否想顯示一個下拉列表來選擇一個'Make',然後讓文本框輸入'Model'和'Year'的數據? (並且表格用於表格數據 - 不用於佈局) –

+0

是的,通過選擇在dorpdownlist中的車輛製造保存數據並在文本框中輸入車型名稱(例如:camry)和年份 –

+0

如何填充VehicleMake列表在下拉菜單中?按模型還是視圖包? – Usman

回答

0

您正在編輯數據,所以第一步是創建視圖模型(根據需要添加其他驗證屬性)。

public class VehicleVM 
{ 
    [Required(ErrorMessage = "...")] 
    public string Model { get; set; } 
    [Required(ErrorMessage = "...")] 
    public DateTime? Year { get; set; } // make nullable to protect against under-posting attacks 
    [Required(ErrorMessage = "...")] 
    [Display(Name = "Make")] 
    public int? SelectedMake { get; set; } 
    public IEnumerable<SelectListItem? MakesList { get; set; } 
} 

和GET方法,初始化您的視圖模型的實例,填充它,並把它傳遞給視圖

var makes = db.VehicleMakes; // get the Makes from the database 
VehicleVM vehicle = new VehicleVM() 
{ 
    MakesList = new SelectList(makes, "MakeId", "Make") 
}; 
return View(vehicle); 

,並在視圖

@model VehicleVM 
.... 
@using (Html.BeginForm()) 
{ 
    @Html.LabelFor(m => m.SelectedMake) 
    @Html.DropDownListFor(m => m.SelectedMake, Model.MakesList) 
    @Html.ValidationMessageFor(m => m.SelectedMake) 

    @Html.LabelFor(m => m.Model) 
    @Html.TextBoxFor(m => m.Model) 
    @Html.ValidationMessageFor(m => m.Model) 

    .... 

這將發佈回到

public ActionResult Create(VehicleVM vehicle) 
0

你的視圖模型應該是這樣的

public VehicleModel VehicleModel { get; set; } 
public List<VehicleMake> VehcileMakeList { get; set; } 

,並在您的視圖

@model MvcApplication1.Data.ViewVMModel 
.... 
<h2>CreateModel</h2> 
<table> 
    <tr> 
     <td>@Html.Label("Select Make")</td> 
     <td>@Html.DropDownListFor(model=>model.VehicleModel.MakeId ,new SelectList(Model.VehcileMakeList, "MakeId","Make")))</td> 
    </tr> 
    <tr> 
     <td>Enter Model </td> 
     <td>@Html.TextBoxFor(model=>model.VehcileModel.Model)</td> 
     <td>@Html.TextBoxFor(model=>model.VehcileModel.Year)</td> 

    </tr> 
</table> 

,並在你的行動

ViewVMModel vm = new ViewVMModel(); 
vm.VehcileMakeList = //get list of make 
vm.VehicleModel = new VehicleModel(); 
return view(vm); 
+0

視圖模型不應包含數據模型! –

相關問題