2014-12-18 70 views
2

返回类“Depot”中的对象,其中包含来自“Gegenstand”类的对象的列表。从视图到控制器的类对象 - > NULL

​​3210

index.cshtml显示列表中的对象。现在我想的对象“Gegenstand”张贴到控制器(注释区)

@model MvcApplication2.Models.Depot 
<table> 
@foreach(MvcApplication2.Models.Gegenstand gegenstand in Model.depotItems) 
{ 
    <tr> 
     <td> 
       @using (Html.BeginForm("Details", "Home", FormMethod.Post)) 
       { 
       // Want to post "Gegenstand" object to controller 
       <input type="submit" value="click" /> 
       } 

     </td> 
    </tr> 
} 
</table> 

这是“详细信息”

[HttpPost] 
    public ActionResult Details(Gegenstand gegenstandObject) 
    { 
     return View(gegenstandObject); 
    } 
+0

你为什么要做'POST'请求来展示一些东西?您需要获取请求,而不是使用对象的ID并在您的详细信息视图中获取它。 –

+1

你只需要在窗体中为每个depotItems属性生成控件(你没有显示出这个模型很难说),但为什么有一个单独的窗体foreach depotItems而不是回发'depotItems'?如果你所做的只是返回视图(你没有保存任何东西),那么POST方法的目的是什么? –

+0

http://www.codeproject.com/Articles/758458/Passing-Data-View-to-Controller-Controller-to-View有一些View-to-Controller的帮助。 – TWhite

回答

2

中的ActionResult你需要建立一个Gegenstand object在您的视图。

您可以实现这两种方式。

在表单中使用MVC中的@Html.EditorFor,并让框架负责模型绑定。

例如:@Html.EditorFor(m => m.YourProperty);

还是通过了建设目标,并通过序列化对象备份到您的Controller。您可以使用JavaScript进行此操作,并使用POST通过AJAX调用回控制器。例如。

<script> 
    function CreateGegenstandObject() { 
     var obj = {}; 
     obj.property = "Your property"; // This should reflect the property in your C# class 
     obj.property2 = "Another property"; // Another property that should be reflected 

     return obj; 
    } 

    function sendGegenstandObjectToController() { 
      var gegenstandObject = CreateGegenstandObject(); 
      $.ajax({ 
      url: '@Url.Action("Details")', 
      type: "POST", 
      data: { gegenstandObject: gegenstandObject.serialize() }, 
      success: function() { alert('success'); } 
      }); 
    } 

</script> 

一旦表单被提交,您将不得不调用sendGegenstandObjectToController函数。

+0

它只适用于Javascript吗? – Donkeyy

+0

@Donkeyy你可以做到这一点ASP.Net MVC风格通过传递对象到控制器上提交 – TWhite

+0

当我有多个对象,我怎么可以只发布我选择的一个? – Donkeyy

相关问题