发布的模型是空的

时间:2014-12-25 23:25:45

标签: asp.net asp.net-mvc asp.net-mvc-5

我有一个ViewModel如下

  public class MetalStockAddVM
{
    public MetalStock MetalStock { get; set; }


    public MetalStockAddVM()
    {
        this.MetalStock=new MetalStock();
    }
}

这是我的控制器

 public class MetalStockController : Controller
{
    private readonly IMetalStockRepository iMetalStockRepository;

    public MetalStockController(IMetalStockRepository iMetalStockRepository)
    {
        this.iMetalStockRepository = iMetalStockRepository;
    }

    // GET: MetalStock
[HttpGet]
    public ActionResult AddMetalStock()
    {
        MetalStockAddVM addVm=new MetalStockAddVM();

        return View(addVm);
    }

[HttpPost]
public ActionResult AddMetalStock([Bind(Include = "MetalStock")]MetalStockAddVM metalStock)
{
    MetalStockDto metalStockDto = new MetalStockDto();

    metalStockDto = Mapper.Map<MetalStock, MetalStockDto>(metalStock.MetalStock);

    iMetalStockRepository.Insert(metalStockDto);

    return RedirectToAction("Index","Home") ;
}

}

这是我的观点

@model LearningSpike.Models.ViewModels.MetalStockAddVM

@using (Html.BeginForm("AddMetalStock","MetalStock",FormMethod.Post))
{
<table>
    <tr>
        <th>
            @Html.LabelFor(m => m.MetalStock.MetalId)
        </th>
        <td>
            @Html.EditorFor(m => m.MetalStock.MetalId)
        </td>

    </tr>
    <tr>
        <th>
            @Html.LabelFor(m => m.MetalStock.GlobalMaterialId)
        </th>
        <td>
            @Html.EditorFor(m => m.MetalStock.GlobalMaterialId)
        </td>

    </tr>
    <tr>
        <th>
            @Html.LabelFor(m => m.MetalStock.Length)
        </th>
        <td>
            @Html.EditorFor(m => m.MetalStock.Length)
        </td>

    </tr>
    <tr>
        <th>
            @Html.LabelFor(m => m.MetalStock.ColourCode)
        </th>
        <td>
            @Html.EditorFor(m => m.MetalStock.ColourCode)
        </td>

    </tr>
    <tr>
        <th>
            @Html.LabelFor(m => m.MetalStock.QuantityInStock)
        </th>
        <td>
            @Html.EditorFor(m => m.MetalStock.QuantityInStock)
        </td>

    </tr>

</table>

<input type="submit" value="Create"/>


}

当我发布传递给控制器​​的模型时,操作方法为空。 请告诉我我做错了什么?我是第一次创建一个建筑峰值所以我可以学到很多东西。这是我第一次实现所有重要的东西(DI,DTO,REpositories等)。我仍然在努力把事情放在正确的位置 谢谢! 干杯!

2 个答案:

答案 0 :(得分:0)

请尝试以下

更改您的型号代码,如下所示

public class MetalStockAddVM
{

  public MetalStock MetalStock { get; set; }

}

然后在AddMetalStock中更改HTTPPOST的Action方法代码,如下所示

[HttpPost]
public ActionResult AddMetalStock(MetalStockAddVM metalStock)
{
    MetalStockDto metalStockDto = new MetalStockDto();

    metalStockDto = Mapper.Map<MetalStock, MetalStockDto>(metalStock.MetalStock);

    iMetalStockRepository.Insert(metalStockDto);

     return RedirectToAction("Index","Home") ;
}

答案 1 :(得分:0)

首先删除[Bind(Include = "MetalStock")],然后将metalStock重命名为metalStockVm之类的内容,并查看它是否有效。

[HttpPost]
public ActionResult AddMetalStock(MetalStockAddVM metalStockVm)