我有一个非常简单的ASP.NET MVC(5.2.4.0)应用程序,代码如下。将表单发布到 [HttpPost] 方法时,我找不到 model.Addresses 为空的原因。有人可以帮帮我吗?对于我所看到的,我的代码与StackOverflow上类似问题的答案相匹配。
HomeController.cs
namespace WebApplication2.Controllers {
public class IndexViewModel {
public string Name { get; set; }
public List<Address> Addresses;
public IndexViewModel()
{
Addresses = new List<Address>();
}
}
public class Address
{
public string Name { get; set; }
public string Id { get; set; }
}
public class HomeController : Controller
{
public ActionResult Index()
{
var model = new IndexViewModel();
model.Addresses = new List<Address>();
model.Addresses.Add(new Address() { Id = "1", Name = "A1" });
model.Addresses.Add(new Address() { Id = "2", Name = "A2" });
return View(model);
}
[HttpPost]
public ActionResult Index(IndexViewModel model)
{
return View(model);
}
}
}
Index.cshml:
@model WebApplication2.Controllers.IndexViewModel
@{
ViewBag.Title = "Home Page";
}
@using (Html.BeginForm("Index", "Home"))
{
@Html.EditorFor(m => m.Name)
for (var i = 0; i < Model.Addresses.Count; i++)
{
@Html.TextBoxFor(m => Model.Addresses[i].Name)
@Html.HiddenFor(m => Model.Addresses[i].Id)
}
<input type="submit" value="Ok" />
}
答案 0 :(得分:0)
正如Tetsuya Yamamoto在上面的评论中提到的,该错误是由于Addresses是公共字段而不是属性。
public List<Address> Addresses;
应更改为
public List<Address> Addresses { get; set; }
答案 1 :(得分:0)
请声明地址为以下属性,因为您将其声明为公共字段而不是属性,因此它无法保存您分配的值。
public List<Address> Addresses{get;set;};