我在for视图中创建了多个表单,当我在提交时发送给控制器并且它为空时问题就出现了。
这是一个例子。@model List<Project.ViewModels.ValidForm>
@if (Model != null)
{
for (int i = 0; i < Model.Count; i++)
{
<div>
@using (Html.BeginForm("Method", "Controller", FormMethod.Post, new { id = "valForm" + @Model[i].Id }))
{
<div class="col-md-4">
<label>Data 1</label><br />
@Html.TextBoxFor(m => m[i].Data1, new { @class = "form-control" })
</div>
<div class="col-md-4">
<label>Data 2 options</label><br />
@Html.TextBoxFor(m => m[i].Data2.Option1, new { @class = "form-control" })
</div>
<div>
<button type="submit" class="btn btn-success">Save this form</button>
</div>
}
</div>
}
}
还有视图模型。
public class ValidForm{
public int data1 { get; set; }
public Data2 data2 {get;set;}
}
public class Data2{
public int option1 {get;set;}
public int option2 {get;set;}
}
和控制器。
[HttpPost]
public ActionResult validaciones(validform vm){
//do something.
return view();
}
答案 0 :(得分:0)
你得到null的原因是你的模型是一个ValidForm数组而不只是一个。
将您的控制器更改为:
[HttpPost]
public ActionResult validaciones(ValidForm[] vms){
ValidForm vm = ValidForm[0];
//do something with vm.
return view();
}
如果你一次只想要一个表格,你可以这样做:(我添加了Name =“PropName”,注意名字中的大写字母N)
然后你应该期待一个VM
<div class="col-md-4">
<label>Data 1</label><br />
@Html.TextBoxFor(m => m[i].Data1, new { @class = "form-control", Name="Data1" })
</div>
对于data2,名称必须是Data2.option1,ect ...
完全正常的例子:
HomeController中:
public class HomeController : Controller
{
public class ValidForm
{
public string Id { get; set; }
public int data1 { get; set; }
public Data2 data2 { get; set; }
}
public class Data2
{
public int option1 { get; set; }
public int option2 { get; set; }
}
public ActionResult Index()
{
var model = new ValidForm[2] { new ValidForm { }, new ValidForm {data2 = new Data2{}} };
return PartialView(model);
}
[HttpPost]
public ActionResult Tester(ValidForm model)
{
return View("Index", new ValidForm[1] { model });
}
}
查看:
@model MvcApplication1.Controllers.HomeController.ValidForm[]
@if (Model != null)
{
for (int i = 0; i < Model.Count(); i++)
{
<div>
@using (Html.BeginForm("Tester", "Home", FormMethod.Post, new { id = "valForm" + @Model[i].Id }))
{
<div class="col-md-4">
<label>Data 1</label><br />
@Html.TextBoxFor(m => m[i].data1, new { @class = "form-control", Name = "data1"})
</div>
<div class="col-md-4">
<label>Data 2 options</label><br />
@Html.TextBoxFor(m => m[i].data2.option1, new { @class = "form-control", Name = "data2.option1"})
</div>
<div>
<button type="submit" class="btn btn-success">Save this form</button>
</div>
}
</div>
}
}
另请注意,输入框只能是数字,因为您拥有全部内容。