将接口从View传递到Controller

时间:2013-11-19 13:27:42

标签: c# asp.net-mvc

我一直试图弄清楚如何通过视图中的表单填充特定的界面。接口与我的控制器/视图的项目和命名空间不同,并且是自动生成的,用于在数据库中存储数据:

接口名称空间和代码:

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) %>
<%:
} 
%>

我所提出的问题是双重的,与观点有关:

  1. 如何告诉视图我想使用位于DataAccess.DAL中的接口,该接口位于与视图不同的项目和命名空间中?
  2. 如何在表单中填充上述界面以将其传递给控制器​​?
  3. 非常感谢任何帮助。

1 个答案:

答案 0 :(得分:1)

你在这里混合了很多概念。

  1. 转到Visual Studio并创建一个新的MVC网站。
  2. 运行它,看看它是如何工作的。
  3. 然后继续google并查找接口的概念。
  4. 回到你新创建的MVC网站,看看你在这里有什么不同。
  5. 编辑: 你正在尝试的是不可能的! 您要求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) %>
    <%:
    } 
    %>