我有以下POCO类:模型绑定不工作
public class Location
{
public int LocationId { get; set; }
public string Name { get; set; }
public string Street { get; set; }
public string City { get; set; }
public string State { get; set; }
public string ZipCode { get; set; }
public string Country { get; set; }
public float? Latitude { get; set; }
public float? Longitude { get; set; }
public string PhoneNumber { get; set; }
public string EmailAddress { get; set; }
public string Website { get; set; }
public virtual ICollection<Program> Programs { get; set; }
public virtual ICollection<PlayerType> PlayerTypes { get; set; }
}
public class PlayerType
{
public int PlayerTypeId { get; set; }
public string Name { get; set; }
public int SortOrder { get; set; }
public bool IsActive { get; set; }
public virtual ICollection<Location> Locations { get; set; }
}
和一个视图模型类
public class LocationViewModel
{
public Location Location { get; set; }
public IList<PlayerType> SelectPlayerTypes { get; set; }
public LocationViewModel()
{
Location = new Location();
}
}
在我创建表单,我已经定义了模型
@model Locator.Models.LocationViewModel
并且有如下字段:
div class="editor-label">
@Html.LabelFor(model => model.Location.Name)
</div>
<div class="editor-field">
@Html.EditorFor(model => model.Location.Name)
@Html.ValidationMessageFor(model => model.Location.Name)
</div>
在我的控制器来处理POST我有
[HttpPost]
public ActionResult Create(LocationViewModel location)
{
if (ModelState.IsValid) {
locationRepository.InsertOrUpdate(location.Location);
locationRepository.Save();
return RedirectToAction("Index");
}
location.SelectPlayerTypes = golferTypeRepository.All.Where(p => p.IsActive).ToList();
return View(location);
}
的问题是,我有一个定位对象,但没有任何属性都设置为在表单中输入的值。
难道我做错了什么吗?
感谢
我可能会关闭,但我认为您在构造函数中初始化'Location'会抛出它。你可以尝试删除该行(并在模型本身之外实例化属性)? –
我在Create ActionResult(不是帖子)中实例化它,现在当我发布时,Location是null。 – Mike
是的,这就是我希望你会尝试的。哦,猜猜这不是问题。 –