从类“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/