我有一个剃刀视图,列出了多个项目。在回发时我想从视图中获取模型以便我可以获取数据,但是当我进行回发时,我对模型数据使用null。我想知道如何在提交时从控制器中的视图中获取数据。 这就是我所拥有的:
查看:
@using Solution.Web.Models
@model ItemsViewModel
@{
ViewBag.Title = "Select Items";
}
@using (Html.BeginForm())
{
foreach (var p in Model.Items)
{
<div class="well">
<span class="pull-right label label-primary">@p.Price.ToString("c")</span>
<span class="lead"><input type="checkbox" data-id="@p.Id" id="Model.Selected" checked="@p.Selected" value="@p.Id" /> @p.Quantity x @p.Name</span>
</div>
}
<div class="well">
<button type="submit" class="btn btn-lg btn-block btn-primary">Pay with Card</button>
<button type="submit" class="btn btn-lg btn-block btn-primary">Pay with PayPal</button>
</div>
}
控制器:
[HttpGet]
public ActionResult Index()
{
ItemsViewModel model = new ItemsViewModel
{
Items = repository.Items
.OrderBy(i => i.Id)
};
return View(model);
}
[HttpPost]
public ActionResult Index(ItemsViewModel items)
{
return View("NextStep");
}
所以在HttpPost上我得到模型的时候,我有空。如何在回发中获得正确的数据集?
这是ItemsViewModel代码:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using Solution.Domain.Entities;
namespace Solution.Web.Models
{
public class ItemsViewModel
{
public IEnumerable<Item> Items;
}
}
提前感谢每个评论,Laziale
答案 0 :(得分:1)
为了使用操作参数映射数据,您的输入必须声明其名称。所以改变你的观点:
@using (Html.BeginForm())
{
for (var i = 0; i < Model.Items.Count(); i++)
{
@{
var p = Model.Items[i];
}
<div class="well">
<span class="pull-right label label-primary">@p.Price.ToString("c")</span>
<span class="lead"> @Html.CheckBoxFor(m => Model.Items[i].Selected, new {"data-id" = p.Id }) @p.Quantity x @p.Name</span>
</div>
}
<div class="well">
<button type="submit" class="btn btn-lg btn-block btn-primary">Pay with Card</button>
<button type="submit" class="btn btn-lg btn-block btn-primary">Pay with PayPal</button>
</div>
}
答案 1 :(得分:0)
这是因为您想要序列化到模型实例的标签的id / name属性。尝试将id更改为Items:
<span class="lead"><input type="checkbox" data-id="@p.Id" id="Items" checked="@p.Selected" value="@p.Id" /> @p.Quantity x @p.Name</span>
我不知道输入是否代表你的项目,也许这是你的整个div:
<div class="well" id="Items">
<span class="pull-right label label-primary">@p.Price.ToString("c")</span>
<span class="lead"><input type="checkbox" data-id="@p.Id" id="Model.Selected" checked="@p.Selected" value="@p.Id" /> @p.Quantity x @p.Name</span>
</div>
答案 2 :(得分:0)
让MVC生成一个包含name
控件Selected[0], Selected[1]
属性的复选框。您需要使用内置的MVC帮助程序类,如下所示
foreach (var p in Model.Items)
{
<div class="well">
<span class="pull-right label label-primary">@p.Price.ToString("c")</span>
<span class="lead">
@Html.CheckBoxFor(m=>m.Selected,{data_id=m.Id})
@p.Quantity x @p.Name</span>
</div>
}
选项2:
@counter=1;
foreach (var p in Model.Items)
{
<div class="well">
<span class="pull-right label label-primary">@p.Price.ToString("c")</span>
<span class="lead">
<input type="checkbox" data-id="@p.Id" id="Model.Selected"
checked="@p.Selected" value="@p.Id" name="Selected[@counter]" />
@p.Quantity x @p.Name</span>
</div>
@counter++;
}