我一直试图弄清楚如何通过视图中的表单填充特定的界面。接口与我的控制器/视图的项目和命名空间不同,并且是自动生成的,用于在数据库中存储数据:
接口名称空间和代码:
DataAccess.DAL.IVehicle
namespace DataAccess.DAL
{
public partial interface IVehicle
{
String vehicleName { get; set; }
int maxSpeed { get; set; }
}
}
我有一个控制器,它有一个动作方法,用于从视图中的表单接收信息:
控制器代码:
namespace coreproject.Controllers
{
public class NewVehicleController
{
[HttpPost, ValidateInput(false)]
public JsonResult AddVechicle(IVehicle newVehicle)
{
// I expect that newVechicle is populated via the form
}
}
}
我知道我应该在视图中使用Html.BeginForm。下面是我想出的一些代码,我理解在视图中需要这些代码。
查看代码:
<%
// This is not working, I am not sure how to tell the view I want the form
// to use the interface located in the following namespace.
@Model DataAccess.DAL.IVehicle;
using (Html.BeginForm("AddVehicle", "NewVechicle", FormMethod.Post))
// Below I understand that I would need some code in the form of Html.EditorFor to
// populate the IVehicle interface in the form. I have seen this as an example:
<%: Html.EditorFor(model => model.VehicleName) %>
<%: Html.EditorFor(model => model.maxSpeed) %>
<%:
}
%>
我所提出的问题是双重的,与观点有关:
非常感谢任何帮助。
答案 0 :(得分:1)
你在这里混合了很多概念。
编辑: 你正在尝试的是不可能的! 您要求MVC框架创建一个接口实例,这是不可能的!
你必须做的是在Action参数中有一个具体的类:
[HttpGet]
public ActionResult AddVechicle()
{
return View(new Vehicle());
}
[HttpPost, ValidateInput(false)]
public JsonResult AddVechicle(Vehicle newVehicle)
{
// I expect that newVechicle is populated via the form
}
然后您可以按如下方式声明“Vehicle”类
public class Vehicle :IVehicle
{
String vehicleName { get; set; }
int maxSpeed { get; set; }
}
我没有测试视图是否接受一个接口作为模型,你最好将它改成“Vehicle”类
<%
// view name: AddVehicle
// This is not working, I am not sure how to tell the view I want the form
// to use the interface located in the following namespace.
@Model Vehicle;
using (Html.BeginForm("AddVehicle", "NewVechicle", FormMethod.Post))
// Below I understand that I would need some code in the form of Html.EditorFor to
// populate the Vehicle concrete class in the form.
<%: Html.EditorFor(model => model.VehicleName) %>
<%: Html.EditorFor(model => model.maxSpeed) %>
<%:
}
%>