首页 文章

为什么列表没有绑定?

提问于
浏览
0

我有一个非常简单的ASP.NET MVC(5.2.4.0)应用程序,代码如下 . 我找不到model的原因 . 当表单发布到[HttpPost]方法时,地址为空 . 有人可以帮帮我吗?我可以看到我的代码在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" />
}

2 回答

  • 0

    请将地址声明为属性,如下所示,因为您将其声明为公共字段而非属性,因此它无法保存您指定的值 .

    public List<Address> Addresses{get;set;};
    
  • 0

    正如上面的评论中提到的那样,错误是由于地址是公共字段而不是属性 .

相关问题