0

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 ?

3
  • Easy, make sure AuthorizedAgent is not null. For any more help than that you're going to need to show us more code. :) Commented Apr 26, 2011 at 14:52
  • What If I want to provide alternate text if some value is null ? Commented Apr 26, 2011 at 14:58
  • 1
    I would create a viewmodel with a property named firstname and then set the property in the controller according if the value is null or not to avoid putting logic in your view. Commented Apr 26, 2011 at 15:02

2 Answers 2

1

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; }
Sign up to request clarification or add additional context in comments.

Comments

0

You have two options here. The first is to ensure the model has a value. Without seeing your code, I have no clue whether this should always have a value or not. The other option is conditionally grabbing the value, which you can do easily in both ASP.NET and Razor view engines.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.