c# - 类对象从 View 到 Controller -> NULL

标签 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”发布到 Controller (评论区)

@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>

这是“详细信息”的 ActionResult

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

最佳答案

您需要在您的 View 中构建一个 Gegenstand 对象

您可以通过两种方式实现这一目标。

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

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

或者通过构建对象并将序列化对象传递回您的 Controller 。您可以使用 JavaScript 执行此操作,并通过 AJAX 调用将其 POST 返回到 Controller 。例如。

<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 函数。

关于c# - 类对象从 View 到 Controller -> NULL,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27556144/

相关文章:

c# - Monitor.TryEnter/Monitor.Exit 和 SynchronizationLockException

c# - WebService GET/POST 调用和 SOAP

c# - 如何在 C# selenium chrome 驱动程序中验证(用户/密码)代理

c# - Autofac 没有找到最贪婪的构造函数

asp.net-mvc - 在asp .net mvc 5中显示外部网站页面

asp.net-mvc - 使用 ASP.NET MVC 2 上传文件的最佳方式是什么?

asp.net-mvc - RouteCollection.Ignore和RouteCollection.IgnoreRoute之间的区别?

javascript - jQuery on click 处理程序未在 asp.net 组件上激活

c# - 如何连接EF中的现有表

数组初始值设定项中的 C# 源代码格式化