I am using following line in my asp.net MVC 3 view.
@Model.AuthorizedAgent.Person.FirstName
But I am getting error because AuthorizedAgent is null. How can I avoid this error ?
I am using following line in my asp.net MVC 3 view.
@Model.AuthorizedAgent.Person.FirstName
But I am getting error because AuthorizedAgent is null. How can I avoid this error ?
You could use a view model with the following property:
@Html.DisplayFor(x => x.AuthorizedAgentFirstName)
and then have the controller perform the necessary tests and populate the property accordingly:
public ActionResult Foo()
{
SomeModel model = ...
SomeViewModel vm = new SomeViewModel();
// TODO: refactor this part to a mapping layer. AutoMapper is
// a good tool for the job
if (model.AuthorizedAgent != null && model.AuthorizedAgent.Person != null)
{
vm.AuthorizedAgentFirstName = model.AuthorizedAgent.Person.FirstName;
}
return View(vm);
}
And in order to provide an alternate text of the value is null you could use the DisplayFormat attribute:
[DisplayFormat(NullDisplayText = "EMPTY")]
public string AuthorizedAgentFirstName { get; set; }