【发布时间】:2013-05-06 09:10:25
【问题描述】:
我有一个非常简单的视图模型,基于客户域模型。
我正在向它添加一个属性:CustomerNameAddress,它由域模型的 CustomerName、Contact 和 Town 组成。
但是,如果 CustomerName、Contact 或 Town 中的任何一个为 null - 那么 CustomerNameAddress 也为 null。
是否在下面的查询中检查 null 并将其更改为“”,以便我的视图模型正常工作?
我试过了:
CustomerNameAddress = (p.CustomerName || "") + ", " + (p.Contact || "") + ", " + (p.Town || "")
... 但 VS 建议操作员 '||'不能应用于'string'和'string'类型的操作数
我的控制器代码如下。
谢谢,
标记
public JsonResult Lookup(string id)
{
string userName = null;
if (HttpContext.User.Identity.IsAuthenticated)
{
userName = HttpContext.User.Identity.Name;
}
var customers = from p in db.Customers
where p.UserName.Equals(userName)
select new CustomerLookupViewModel
{
CustomerId = p.CustomerId,
Email = p.Email,
CustomerNameAddress = p.CustomerName + ", " + p.Contact + ", " + p.Town
};
return Json(customers, JsonRequestBehavior.AllowGet);
}
更新
我将代码修改为:
但现在 p.Contact 上出现错误(上面加下划线)建议:无法将类型 'string' 隐式转换为 'bool'
但是,我的视图模型显然将联系人作为字符串:
public class CustomerLookupViewModel
{
public string CustomerNameAddress { get; set; }
public int CustomerId { get; set; }
[Required]
[Display(Name = "Customer Name")]
public string CustomerName { get; set; }
[Display(Name = "Customer Contact")]
public string Contact { get; set; }
第二次更新 - 正在运行
我更新了要括在括号中的条件,它现在可以工作了:
CustomerNameAddress = ((p.CustomerName == null) ? "" : (p.CustomerName + ", ")) +
((p.Contact == null) ? "" : (p.Contact + ", ")) +
((p.Town == null) ? "" : (p.Town))
【问题讨论】:
标签: asp.net asp.net-mvc linq viewmodel