【发布时间】:2012-05-31 09:58:59
【问题描述】:
我有以下 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 对象,但没有一个属性可以设置为表单中输入的值。
我在这里做错了吗?
谢谢
【问题讨论】:
-
我可能会离开,但我认为你在构造函数中初始化
Location是把它扔掉了。您可以尝试删除该行(并在模型本身之外实例化该属性)吗? -
我在 Create ActionResult(不是帖子)中实例化了它,现在当我发布时,Location 为空。
-
是的,这就是我希望你尝试的方法。哦,好吧,我猜这不是问题。
-
当您说所有属性都不能设置为表单中输入的值时 - 您在哪里/如何确定这一点?
-
我将 Create 构造函数更新为 public ActionResult Create(LocationViewModel model, Location location) 并且它正在工作。