从视图到控制器的类对象 - >空值

时间:2014-12-18 21:36:36

标签: c# .net asp.net-mvc asp.net-mvc-4 model-view-controller

从类" Depot"返回一个对象。其中包含一个包含来自" Gegenstand"的对象的列表。类。

    public ActionResult Index()
    {
        Depot depotObject = new Depot();
        Gegenstand gegenstandObject = new Gegenstand { Beschreibung = "Door" };
        depotObject.depotItems.Add(gegenstandObject);
        return View(depotObject);
    }

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>

这是&#34;详细信息&#34;

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

1 个答案:

答案 0 :(得分:2)

您需要在视图中构建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函数。