表单提交时,Controller action方法的model参数为空
我在Movie控制器中有一个动作方法ReleasingTheaters,ReleasingTheaters有两个重载,一个是httpGet,它接受Movie Id并做东西并返回ReleasingTheaters View,它接受一个ViewModel对象。当我通过点击提交提交表单时,ReleasingTheaters视图按钮,控制器的另一个http Post动作方法ReleasingTheaters接受viewModel并将模型数据保存到数据库。
这是我的viewModel:
public class MovieReleasingTheatersViewModel { public MovieReleasingTheatersViewModel() { AvailableStates = new List(); AvailableCities = new List(); AvailableLocations = new List(); ReleasingTheaters = new List(); } [Display(Name="State")] public int? StateId { get; set; } public IList AvailableStates { get; set; } [Display(Name = "City")] public int? CityId { get; set; } public IList AvailableCities { get; set; } public int? LocationId { get; set; } public IList AvailableLocations { get; set; } public IList ReleasingTheaters { get; set; } }
这是我的控制:
[HttpGet] public ActionResult ReleasingTheaters(int id) { var model = new MovieReleasingTheatersViewModel(); model = PrepareMovieReleasingTheaterModel(0, 0, 0, id); return View(model); } [HttpPost] [ValidateAntiForgeryToken] public ActionResult ReleasingTheaters(MovieReleasingTheatersViewModel model) { // iterate through the model's collection and save or update database return View("Index"); }
这是我的释放剧院观点:
@model Bookmany.Admin.Models.Movie.MovieReleasingTheatersViewModel @{ ViewBag.Title = "Releasing Theaters"; } Releasing Theaters
@using (Html.BeginForm()) { @Html.AntiForgeryToken() @Html.DropDownListFor(model => model.StateId, Model.AvailableStates, "Select State") @Html.DropDownListFor(model => model.CityId, Model.AvailableCities, "Select City") @Html.DropDownListFor(model => model.LocationId, Model.AvailableLocations, "Select Location")
Theater Date From Date To Release @foreach (var item in Model.ReleasingTheaters) { @Html.DisplayFor(modelItem => item.TheaterName) @Html.TextBoxFor(modelItem => item.DateFrom, new { id = "DateFrom" }) @Html.TextBoxFor(modelItem => item.DateTo, new { id = "DateTo" }) @Html.EditorFor(modelItem => item.IsTheaterChecked) }
}
我的问题 :
当我单击提交按钮时,对象on action方法没有值,viewModel对象的集合属性都是空的,我的代码是错的
如何在我的操作方法上获取模型对象值(集合),以便我可以将该值保存或更新回我的数据库
您需要将foreach
更改for
循环,以便控件正确命名并且可以由DefaultModelBinder
绑定
@for (int i = 0; i < Model.ReleasingTheaters.Count; i++) { @Html.TextBoxFor(m => m.ReleasingTheaters[i].DateFrom) .... }
这将生成诸如的输入
另请注意,您不应该使用new { id = "DateFrom" }
等设置id
属性。帮助器将呈现唯一的ID,但您创建的重复ID是无效的html
- 如何在ASP.NET MVC应用程序中附加自定义成员资格提供程序?
- 同时访问MVC .NET上的数据
- ASP.NET返回多个变量以查看
- MVC身份validation – 最简单的方法
- 在RedirectToAction中传递对象
- 从adlds实例validationasp.net mvc 5应用程序
- MVC2 ASP.Net URL会自动解码吗?
- 以编程方式在asp.net应用程序上的microsoft.identityModel中配置federatedAuthentication元素
- 如果在Code First模式下使用,使用T4模板为Database First和Model First开发生成的代码可能无法正常工作