最近尝试将我的代码从mvc5升级到asp.net核心 我试图将一个复杂的对象从razor视图发布到我的控制器,但是什么也没有发布。我应该提出什么才能使它起作用?
发布此消息时,我的Matchresult VM始终为空。 for循环中的@ Html.TextBoxFor(x => x.SetResults [i] .Team1Result)是否正确? 我的模型和视图模型
public class Match
{
[Key]
public int MatchID { get; set; }
public DateTime Matchdate { get; set; }
public string MatchNote { get; set; }
public int RoundID { get; set; }
public virtual Round MatchBelongsToRound { get; set; }
public int? Team1Id { get; set; }
public virtual Team Team1 { get; set; }
public int? Team2Id { get; set; }
public virtual Team Team2 { get; set; }
public int? WinningTeamId { get; set; }
public virtual Team WinningTeam { get; set; }
public int? DivisionID { get; set; }
public virtual Division Division { get; set; }
public bool isPlayed { get; set; }
}
public class SetResult
{
public int SetResultID { get; set; }
public int Team1Result { get; set; }
public int? Team1Id { get; set; }
public virtual Team Team1 { get; set; }
public int Team2Result { get; set; }
public int? Team2Id { get; set; }
public virtual Team Team2 { get; set; }
public int? MatchID { get; set; }
public virtual Match Match { get; set; }
public int SetOrder { get; set; }
}
public class MatchResultVM
{
public MatchResultVM()
{
SetResults = new List<SetResult>();
}
public virtual Match Match { get; set; }
public virtual List<SetResult> SetResults { get; set; }
}
[HttpPost]
public IActionResult labb([FromForm] MatchResultVM vm)
{
return RedirectToAction("labb/5");
}
答案 0 :(得分:0)
似乎向我发布了一个嵌套模型问题。请确保使用的嵌套符号设置所有模型属性的name
属性。运算子SetResults[0].Team1Result
。这应该由@Html
个辅助方法自动处理。请检查您是否为模型正确生成了HTML,如下所示:
@model MatchResultVM
for (var i = 0; i < Model.SetResults.Count(); i++)
{
@Html.TextBoxFor(x => Model.SetResults[i].Team1Result)
@Html.TextBoxFor(x => Model.SetResults[i].Team2Result)
...
}
上面的代码应生成如下的HTML:
<input name="SetResults[0].Team1Result" id="SetResults_0__Team1Result" />
<input name="SetResults[0].Team2Result" id="SetResults_0__Team2Result" />
<input name="SetResults[1].Team1Result" id="SetResults_1__Team1Result" />
<input name="SetResults[1].Team2Result" id="SetResults_1__Team2Result" />
...
在Asp.Net Core中,您还可以利用TagHelpers
而不是HtmlHelpers
,因此可以使用输入TagHelper编写如下所示的for循环。有关TagHelpers的更多信息,请参见此link
for (var i = 0; i < Model.SetResults.Count(); i++)
{
<input asp-for="@Model.SetResults[i].Team1Result" />
<input asp-for="@Model.SetResults[i].Team2Result" />
...
}
如果您还可以发布剃刀视图,则有助于了解发生了什么情况