Asp.net mvc 如何在MVC中使用强类型视图绑定一个用于创建dropdownlist的模型和文本框的第二个模型?

Asp.net mvc 如何在MVC中使用强类型视图绑定一个用于创建dropdownlist的模型和文本框的第二个模型?,asp.net-mvc,asp.net-mvc-4,Asp.net Mvc,Asp.net Mvc 4,第一款: 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 Dat

第一款:

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; }
}
如何将两个模型作为强类型视图传递

我的视图有1)一个dropdownlist,它从VehicleMake类绑定make和makeid 2) 一个文本框作为从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>
@model mvcapapplication1.Data.ViewVMModel
....
创建模型
@标签(“选择制作”)
@DropDownListFor(model=>model.VehicleMake,新选择列表(model.MakeId,Make)))
进入模型
@Html.TextBoxFor(model=>model.VehcileModel)

您正在编辑数据,因此第一步是创建视图模型(根据需要添加其他验证属性)

在我看来

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

您的Viewmodel应该是这样的

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

VehcileModel
是一个复杂对象,不能将文本框绑定到复杂对象。是否要显示下拉列表以选择一个
Make
,然后使用文本框为
Model
Year
输入数据?(表格用于表格数据-不要将其用于布局)是的,通过在dorpdownlist中选择车辆制造来保存数据,并在文本框中输入车型名称(例如:凯美瑞)和年份如何填充车辆制造下拉列表?按模型还是按viewbag?视图模型不应包含数据模型!
public ActionResult Create(VehicleVM vehicle)
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);