开发者

Null reference error in asp.net MVC3

I am using foll开发者_如何学Pythonowing 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; }


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜