C# post后返回空模型
似乎很多人都有这个问题,但我还没有找到解决我的具体案例的方法 我先把票送到我的观点C# post后返回空模型,c#,asp.net,asp.net-mvc,razor,model-binding,C#,Asp.net,Asp.net Mvc,Razor,Model Binding,似乎很多人都有这个问题,但我还没有找到解决我的具体案例的方法 我先把票送到我的观点 [HttpGet] public ActionResult AddPopcorn() { List<Ticket> tickets = new List<Ticket>(); // Fill the list with tickets return View("AddPopcorn", tickets); } [Ht
[HttpGet]
public ActionResult AddPopcorn()
{
List<Ticket> tickets = new List<Ticket>();
// Fill the list with tickets
return View("AddPopcorn", tickets);
}
[HttpGet]
公共行动结果爆米花()
{
列表票证=新列表();
//把票填在名单上
返回视图(“添加爆米花”,门票);
}
在视图中,我使用表单和复选框显示票据。该视图正确显示票据
@model List<Domain.Entities.Ticket>
@{
ViewBag.Title = "AddPopcorn";
}
<body>
// Html stuff
@using (Html.BeginForm("AddPopcorn", "Ticket", FormMethod.Post))
{
<table>
@foreach (var item in Model)
{
<tr>
<td>
@Html.DisplayFor(modelItem => item.TicketID)
</td>
<td>
@Html.DisplayFor(modelItem => item.Price)
</td>
<td>
@Html.DisplayFor(modelItem => item.TicketType)
</td>
<td>
@Html.CheckBoxFor(modelItem => item.Popcorn)
</td>
</tr>
}
</table>
<input type="submit" value="Voeg toe!" />
}
</div>
</body>
@型号列表
@{
ViewBag.Title=“添加爆米花”;
}
//Html内容
@使用(Html.BeginForm(“AddPopcorn”,“Ticket”,FormMethod.Post))
{
@foreach(模型中的var项目)
{
@DisplayFor(modelItem=>item.TicketID)
@DisplayFor(modelItem=>item.Price)
@DisplayFor(modelItem=>item.TicketType)
@CheckBoxFor(modelItem=>item.Popcorn)
}
}
如果人们选中该复选框,我希望“爆米花”的值为真。因此,我希望视图返回一个带有基于复选框的爆米花更新值的票证列表
[HttpPost]
public ActionResult AddPopcorn(List<Ticket> model)
{
foreach (var item in model)
{
if (item.Popcorn == true)
{
item.Price = item.Price + 5;
}
}
return RedirectToAction("Payment", "Payment");
}
[HttpPost]
公共行动结果添加爆米花(列表模式)
{
foreach(模型中的var项目)
{
如果(item.Popcorn==true)
{
项目价格=项目价格+5;
}
}
返回操作(“付款”、“付款”);
}
但是,返回到AddPopcorn的模型为空。我似乎不明白为什么。这是因为您的表单实际上没有将任何数据发回控制器 您需要输入元素才能从表单中检索数据 相反,在控制器上,通过以下方式访问模型:
var model = this.Model
表单将仅发送您在输入标签中获得的数据,例如
<input type="text" name="first_name" />
尝试将
foreach
循环更改为for
:
for (int i = 0; i < Model.Count; i++)
{
<tr>
<td>
@Html.DisplayFor(x => Model[i].TicketID)
</td>
<td>
@Html.DisplayFor(x => Model[i].Price)
</td>
// etc
<td>
@Html.CheckBoxFor(x => Model[i].Popcorn)
</td>
</tr>
}
for(int i=0;iModel[i].TicketID)
@DisplayFor(x=>Model[i].Price)
//等
@Html.CheckBoxFor(x=>Model[i].爆米花)
}
默认的模型绑定器使用特定的约定来确定如何绑定项目列表,例如model[0]。Popcorn
(name)。您可以检查复选框的HTML是否将name
属性设置为该格式
除了为使用
之外,您还可以为您的票证
对象指定一个自定义的编辑器或模板。很有效,谢谢!如果这对您有效,如果您能接受这一回答,我将不胜感激,谢谢。有没有办法让它将发送到视图的所有数据发送回?现在,我用tempdata更新了以前型号的列表,list ticketList=(list)tempdata[“Tickets”];但这并不是最好的解决方案。