【发布时间】:2019-09-03 18:11:19
【问题描述】:
我正在尝试将复杂的数据结构从控制器传递到视图并返回到包含列表的控制器。我可以在视图中看到列表项。我想编辑这些并将其发送回控制器。我可以编辑一些属性,但对于列表,我在控制器中得到空值。
这是我想要实现的示例(模拟):
考虑模型 -
using System.Collections.Generic;
namespace WebApplication1.Models
{
public class StudentViewModel
{
public string StudentId { get; set; }
public string FeedBack { get; set; }
public List<ScoreCard> ScoreCards;
}
public class ScoreCard
{
public string Subject { get; set; }
public string Marks { get; set; }
}
}
控制器 -
public class StudentController : Controller
{
public ActionResult Index()
{
var model = new StudentViewModel();
model.StudentId = "Some Student";
model.ScoreCards = new List<ScoreCard>
{
new ScoreCard()
{
Marks = "0",
Subject = "English"
},
new ScoreCard()
{
Marks = "0",
Subject = "Maths"
}
};
return View("View", model);
}
public ActionResult SubmitScore(StudentViewModel model)
{
/* Some Code */
}
}
查看-
@model WebApplication1.Models.StudentViewModel
@{
ViewBag.Title = "Title";
}
@using (Html.BeginForm("SubmitScore", "Student", FormMethod.Post))
{
@Html.DisplayName(@Model.StudentId)<br />
<label>Comment:</label><br/>
@Html.EditorFor(m => m.FeedBack, new { htmlAttributes = new { @type = "text", id = @Model.FeedBack} })<br />
for (var i = 0; i < @Model.ScoreCards.Count; i++)
{
@Html.DisplayName(@Model.ScoreCards[i].Subject) <br/>
@Html.EditorFor(m => m.ScoreCards[i].Marks, new { htmlAttributes = new { @type = "number", @min = 0, id = @Model.ScoreCards[i].Marks} })<br />
}
<input class="btn btn-primary" type="submit" value="Submit" />
}
当我运行应用程序时 -
当我点击提交时,我可以看到model.FeedBack,但列表设置为空。
在这个question 中实现了类似的东西,这是答案;我不确定我到底错过了什么。
【问题讨论】:
标签: c# asp.net-mvc razor model-view-controller