Mik*_*ike 9 asp.net-mvc asp.net-mvc-3
我有以下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; }
}
Run Code Online (Sandbox Code Playgroud)
和视图模型类
public class LocationViewModel
{
public Location Location { get; set; }
public IList<PlayerType> SelectPlayerTypes { get; set; }
public LocationViewModel()
{
Location = new Location();
}
}
Run Code Online (Sandbox Code Playgroud)
在我的创建表单中,我已将模型定义为
@model Locator.Models.LocationViewModel
Run Code Online (Sandbox Code Playgroud)
并有以下字段:
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>
Run Code Online (Sandbox Code Playgroud)
在我的控制器中处理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);
}
Run Code Online (Sandbox Code Playgroud)
问题是我有一个Location对象,但没有任何属性要设置为在表单中输入的值.
我在这里做错了吗?
谢谢
Dar*_*rov 46
这是问题所在:
[HttpPost]
public ActionResult Create(LocationViewModel location)
Run Code Online (Sandbox Code Playgroud)
你看到了吗?这是你的行动论点的名称:location
.
现在看看你的视图模型,它有一个名为的属性Location
:
public Location Location { get; set; }
Run Code Online (Sandbox Code Playgroud)
这会混淆模型绑定器.它不再知道您是否需要绑定LocationViewModel
它的属性.
所以只需重命名以避免冲突:
[HttpPost]
public ActionResult Create(LocationViewModel model)
Run Code Online (Sandbox Code Playgroud)
小智 33
只是为了贡献另一个可能的原因:我花了几个小时在我的代码中查找错误,并且在我的情况下绑定器不起作用的原因是使用具有公共字段而不是公共属性的模型:
public int CustomerName;
Run Code Online (Sandbox Code Playgroud)
它应该是:
public int CustomerName { get; set; }
Run Code Online (Sandbox Code Playgroud)
从未在ASP.NET MVC工作3年了,我之前从未见过这个.希望它能为某些人带来一些挫败感;)
归档时间: |
|
查看次数: |
21090 次 |
最近记录: |