我有一个模型类库,它定义了WebAPI中用于JSON序列化的DTO,以及ASP.NET MVC中的模型传输。因为它们是两个函数的模型,所以我使用DisplayAttribute和JsonPropertyAttribute (Newtonsoft.Json)装饰我的模型类,以给出一个可读的标签以及一个完全不同的序列化属性名称。我发现用这两个属性修饰的类属性丢失了它们的标签,而是显示了属性名(例如,"CompanyCode“而不是”公司代码“)。是否有已知的DisplayAttribute和JsonPropertyAttribute之间的兼容性问题会导致这种情况?也许是一种没有明确记载的优先顺序?
我真的不希望在MVC项目中复制我的类,而只是将属性装饰缩减到一个。我讨厌重复的代码。下面是这个问题的一个例子:
public class Store {
// This one doesn't work in Razor:
[Display(Name = "Company Code")]
[JsonProperty(PropertyName = "company_code")]
public string CompanyCode { get; set; }
// This one works in Razor without the JsonPropertyAttribute:
[Display(Name = "Store Name")]
public string Name { get; set; }
}Razor的观点:
@model MyProject.Models.Store
<div>
@Html.LabelFor(model => model.CompanyCode, htmlAttributes: new { @class = "control-label" })
@Html.EditorFor(model => model.CompanyCode, new { htmlAttributes = new { @class = "form-control" } })
</div>
<div>
@Html.LabelFor(model => model.Name, htmlAttributes: new { @class = "control-label" })
@Html.EditorFor(model => model.Name, new { htmlAttributes = new { @class = "form-control" } })
</div>WebAPI控制器方法:
public HttpResponseMessage GetStore(string companyCode) {
return Request.CreateResponse(HttpStatusCode.OK, new MyProject.Models.Store {
CompanyCode = companyCode,
Name = "New Store"
});
}由于更新的行为与这两个属性不一致,而且我无法使其工作,所以我决定使用转换方法创建一个专用的ViewModel类。为了获得更多信息,下面是新代码:
public sealed class Store {
[JsonProperty(PropertyName = "company_code")]
public string CompanyCode { get; set; }
public string Name { get; set; }
}
public sealed class StoreModel {
[DisplayName("Company Code")]
public string CompanyCode { get; set; }
[Required]
public string Name { get; set; }
public static StoreModel FromStore(Store store) {
return new StoreModel {
CompanyCode = store.CompanyCode,
Name = store.Name
};
}
public Store ToStore() {
return new Store {
CompanyCode = CompanyCode,
Name = Name
};
}
}发布于 2015-08-17 20:20:33
请将属性显示更改为DisplayName:
[DisplayName("Company Code")]我的完整代码:
public class User
{
public int Id { get; set; }
public string Name { get; set; }
[DisplayName("Last Name")]
[JsonProperty(PropertyName = "last_name")]
public string LastName { get; set; }
}
public class HomeController : Controller
{
public ActionResult Index()
{
var user = new User()
{
Id = 1, Name = "Julio", LastName = "Avellaneda"
};
return View("Index", user);
}
}
public class UsersController : ApiController
{
public HttpResponseMessage Get()
{
return Request.CreateResponse(HttpStatusCode.OK, new User
{
Id = 1, Name = "Julio", LastName = "Avellaneda"
});
}
}如果我在fiddler中测试web端点:

我的观点是:

致以敬意,
https://stackoverflow.com/questions/32058730
复制相似问题