假设我有以下观点:
@model CityViewModel
@Html.EditorFor(model => model.City.Name) @* This is fine *@
Welcome to @Model.City.Name @* This will error *@
我在@ Model.City.Name上收到以下错误:Object reference not set to an instance of an object.
如何直接从视图模型中获取值?...
------------请注意,除了CityViewModel还有更多内容,只是我已经删除了敏感名称----------- ------
我的CityViewModel混合了City,State,Country类型......它们只是ViewModel中该类型的属性:
public class CityViewModel
{
[Display(Name = "City")]
public City City;
[Display(Name = "Country")]
public Country Country;
}
然后我用Linq连接获取这些东西,然后用它返回一个CityViewModel:
public CityViewModel CVMGetByID(int cityID)
{
var cityViewModel =
from _ in context._
join address in context.Addresses on _.AddressID equals address.AddressID
join city in context.Cities on address.CityID equals city.CityID
join country in context.Countries on address.CountryID equals country.CountryID
join state in context.States on address.StateID equals state.StateID
where _._ID == _ID
select new CityViewModel ();
return cityViewModel.SingleOrDefault();
}
答案 0 :(得分:2)
我注意到您在视图模型中使用的是字段,而不是属性。也许这种变化:
public City City;
到
public City City { get; set; }
将解决您的问题。
答案 1 :(得分:0)
您是否只将一个对象传递给视图或对象列表? 如果是列表,请尝试:
@Model.City[0].Name
答案 2 :(得分:0)
可能会从您的查询中分配数据。 像
这样的东西...
select new CityViewModel {
City = _City;
};
等等。