It's really a nitty-gritty issue for me, and I have been here many times before. How could this be improved?
I have a basic viewmodel for a view:
public class LoginViewModel : BaseViewModel
{
public User _User { get; set; }
}
My base class looks like this:
public class BaseViewModel
{
public List<string> StateMessages { get; set; }
}
The view takes a LoginViewModel
, but if I do not pass it in from the controller, then I need to check the StateMessages
for null before I access it. So I pass in an empty ViewModel
, which is okay, but if I could get around it, it would just look better.
[Route("login")]
[Route( "~/", Name="default" )]
public ActionResult Login()
{
if (User.Identity.IsAuthenticated)
return RedirectToAction("Index", "Dashboard");
return View(new LoginViewModel());
}
Then in the view I don't have check for null, which I prefer:
@foreach (var err in Model.StateMessages)
{
<span>@err</span><br />
}
I know this is very cosmetic, but is this just they way it should be, or can I somehow avoid to new up a new and empty ViewModel
in the controller?
1 Answer 1
I would suggest changing the type of StateMessages
from List<string>
to IEnumerable<string>
.
It hides implementation details, allowing you flexibility in your choice of data structure in the future.
It also gives you more control over how client code can access/modify the state messages.
Make the backing field readonly
to ensure that it's not null.
public class BaseViewModel
{
private readonly List<string> stateMessages = new List<string>();
public IEnumerable<string> StateMessages
{
get { return this.stateMessage; }
}
// Other methods to access/modify stateMessages.
}
null check
? Where and how do you pass an emptyViewModel
? I have deleted my answer so it is legit to add more code. \$\endgroup\$